Admin 2008 -->
Debian Linux Admin – Useful One-Liners
Copy an MBR
Use: # dd if=/dev/sda of=/mbr bs=512 count=1
to copy and...
Use: # dd if=/mbr of=/dev/hda bs=1 count=64 skip=446 seek=446
to write it back
This is the WinNT cmd line for dd-0.5 that copies from the unmounted hidden partition0 on a Vista pc:
dd.exe if=\\?\Device\Harddisk0\Partition0 of=\\.\d:/mbr bs=512 count=1
DYNDNS
#ddclient -query
Learn VIM!!! Or another non-X windows text editor like Nano etc.
# apt-get install vim
# vimtutor
You can open a file at specific word using # vi +/"word" /file.txt or at a line number
#vi +30 /webmin-setup.out
#cat -n /xpkgs.txt (adds line numbers to file contents)
# arp -a
# hdparm -i /dev/hda - gives all info on device:
#finger username
#apt-get install bwm-ng (bandwidth monitor)
#grpck - checks group files integrity:
#blkid /dev/hda1 – find what filesystem is on a partition
#less /proc/net/bonding/bond0 – info on bonded ethernet cards
#rsync --dry-run -e ssh --verbose --progress --stats --compress --recursive --times --perms --links --delete --exclude "/sys" --exclude "/dev" --exclude "/proc" --exclude "*bak" /* user@remoteserver.com:backupfolder
(..Notice the --dry-run option to just test the transfer without actually sending files. Note also the --delete option to delete any files in the remote location that no longer exist on the local server. Finally note the -e ssh to ensure the transfer is actually secure. Once you are happy the process is working simple remove the –dry-run)
du -ah /LVM80G/
df -h /dev/sda1
#route add -net default gw x.x.x.x (sets the default gateway for pc with static IP set via
#ifconfig
can be automated at boot by adding gateway=x.x.x.x to /etc/network/interfaces file
# grep $stg /filename
ls -a /share/ | grep "^f" (find a file in /share beginning with "f")
ls -a /share/ | grep "[^f]^f" (find a file in /share NOT beginning with "f" - NOTE diff meanings of ^ inside [ie NOT = ] or outside the []s), ie ^=start of line..!
Like solving crosswords..? Use the "." for a single character match of 5 letter words starting with c and ending with h: # grep " \ < c...h \ > " /usr/share/dict/words
You can also OP the contents of a whole file like using #cat by finding ALL the chars in a file eg: #grep '.*' /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
...trunc...Also, my grep OP is colorised green for easy result view from editing the .bashrc file in home dir, and adding grep = grep -r as an alias, as other examples given
DMESG (gives debug info of current startup events) and Notices
# dmesg
or can be read/searched directly from file: # vi /var/log/dmesg
Edit /etc/syslog.conf removing the # on the news, debug and notice /dev/tty8 lines as below to show system notices, like info on a newly plugged USB stick etc. Press Ctrl-Alt-F8 to see tty8.
# I like to have messages displayed on the console, but only on a virtual
# console I usually leave idle.
#daemon,mail.*;\
news.=crit;news.=err;news.=notice;\
*.=debug;*.=info;\
*.=notice;*.=warn /dev/tty8
find . -type f -not -empty | wc -l
firewall:~# apropos find
chkdupexe (1) - find duplicate executables
dcopfind (1) - Find the DCOP reference of a KDE service
exinext (8) - Finding individual retry times
exiwhat (8) - Finding out what Exim processes are doing
find (1) - search for files in a directory hierarchy
find2perl (1) - translate find command lines to Perl code
findaffix (1) - Interactive spelling checking
findfs (8) - Find a filesystem by label or UUID
findsmb (1) - list info about machines that respond to SMB name queries on a subnet
gift (1) - GNU Image Finding Tool - index and search images by content
gift-add-collection.pl (1) - GNU Image Finding Tool - index and search images by content
gift-diagnose-print-all-ADI.pl (1) - GNU Image Finding Tool - index and search images by content
gift-dtd-to-keywords.pl (1) - GNU Image Finding Tool - index and search images by content
gift-dtd-to-tex.pl (1) - GNU Image Finding Tool - index and search images by content
gift-endianize (1) - GNU Image Finding Tool - index and search images by content
gift-extract-features (1) - GNU Image Finding Tool - index and search images by content
gift-generate-inverted-file (1) - GNU Image Finding Tool - index and search images by content
gift-modify-distance-matrix (1) - GNU Image Finding Tool - index and search images by content
gift-mrml-client.pl (1) - GNU Image Finding Tool - index and search images by content
gift-old-to-new-url2fts.pl (1) - GNU Image Finding Tool - index and search images by content
gift-one-minus (1) - GNU Image Finding Tool - index and search images by content
gift-perl-example-server.pl (1) - GNU Image Finding Tool - index and search images by content
gift-remove-collection.pl (1) - GNU Image Finding Tool - index and search images by content
gift-start.pl (1) - GNU Image Finding Tool - index and search images by content
gift-url-to-fts.pl (1) - GNU Image Finding Tool - index and search images by content
gift-write-feature-descs (1) - GNU Image Finding Tool - index and search images by content
gnuift (1) - GNU Image Finding Tool - index and search images by content
hal-find-by-capability (1) - find device objects by capability matching
hal-find-by-property (1) - find device objects by property matching
kappfinder (1) - searches for program to add to the Kde menu
kfind (1) - KDE find tool
locate (1) - find files by name
mlocate (1) - find files by name
oldfind (1) - search for files in a directory hierarchy
pidof (8) - find the process ID of a running program.
recursdir (1) - recurse through local or remote directories to command/find files or create tar files.
runlevel (8) - find the previous and current system runlevel.
sane-find-scanner (1) - find SCSI and USB scanners and their device files
Mirrordir
mirrordir is a DANGEROUS command because files or directories that exist in mirror that don't exist in control are deleted. If control is entirely empty, then all files and directories in mirror will be deleted. If mirror is entirely empty, then all files and directories in control will be copied.
#mirrordir -v /source_dir /destination_dir (mirrors, copies recursively, an exact clone of a directory/whole OS, great for cloning an installed Linux OS to transfer to 2nd pc.
Dont forget the –dry-run! Check its doing what it should before you wipe your disk by accident!!
Use -v so you can see progress and use the –exclude /unwanted_dir to stop recursive mount copy of a copy.
Ctrl-C to abort as usual to stop prog
#. vi /etc/network/interfaces (edit with vim, the net conf file for static ip or dhcp )
# The loopback network interface
auto lo
iface lo inet loopback
auto eth1
iface eth1 inet static
address 192.168.1.10
netmask 255.255.255.0
gateway 192.168.1.1
#mount -t cifs //server/share /dir -o username=user (Note: this CIFS [Common Inet File Sys] format now supercedes SMBFS to mount a XP/Vista share on Linbox via Samba. Note, Vista security requires Netcard having Netbios, port 139 enabled in Properties/Advanced/WINS tab)
#netstat -an | grep ssh (searches for string with particular number associated eg for seeing connection state info on a network service eg ssh/apache2 service connected or listening, [also use # nmap 127.0.0.1] )
#nmap -PO x.x.x.x (uses varied pings to try penetrate a stealthed IP)
#tcpdump -vv eth0 ( 2 Vs - puts netcard into promiscuous listening mode to view, Very Verbosely, bcast address info, eg to find a lost subnet addr on a preconfigugreen net device with no reset to default button)
#socat (netcat on steroids supposedly - look into this...)
# socat - TCP:localhost:www,crnl (fetches whole webpage.html after 2 way pipe is open and GET / typed)
GET /
#vim .bashrc (edits user .bashrc file using vim editor to get colourisation for ls -al and grep listings etc.)
#pwgen (generates 8 digit passwords of varying complexity)
#man pwgen (manual page for program... if it exists..or try "info")
#apt-get install linux-image* (lists all available image names for current architecture, i386, AMD64 etc. can search any packages using wildcard * like this also)
#apt-get install knemo (config via Control Panel for taskbar network icons and info)
#apt-cache pkgnames | sort > pkgs.txt (outputs all the 30000 odd package names available for install on Debian, pipes output via sort to list them alphabetically, and saves list as a textfile)
#apt-cache pkgnames | wc -l (pipes packagenames via word count with a -l line switch to give a total count of all packages, = 30107 for this kernel version)
#uname -a (gives full kernel version info = Linux t5500 2.6.26-1-686 #1 SMP Thu Oct 9 15:18:09 UTC 2008 i686 GNU/Linux)
#scp ~/.ssh/id_rsa.pub username@remoteserver.com:.ssh/auth_keys (secure copy of public keys to remote server .ssh/auth_keys file to enable passwordless logins/transfers via rsync)
ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key
ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key
This allows logging info from a Cisco/WinServer to be logged by Debian in the enterprise.log. The Cisco IOS device has to be configd with:
# config term
# logging
# logging trap (3,4,7 level etc.)
# service timestamps log datetime
# logging on
When done, stop the syslogd server with #/etc/init.d/rsyslogd stop
Restart with #/etc/ini.d/rsyslogd restart (listens for remote log info.)
# file /pkgs.txt /bin/vdir (tells file types of each file)
#comm /f1 /f2 (compare two sorted files line by line)
#cmp - compare two files byte by byte
#diff (compare two files line by line)
#ls -al /bin/ | wc -l (the -l switch for wc is for "lines")
#ls -alsh /mnt/
#invoke (alternative to /etc/init.d/service start|stop|restart)
#tar -xvf filename.tar (recursively unpacks a tarball file)
#wpa_passphrase essid-name wpa-password > /etc/wpa_supplicant/wpa_supplicant.conf (creates a basic wpa conf file), then run:
#wpa_supplicant -Dwext -iwlan0 -c/etc/wpa_supplicant/wpa_supplicant.conf
(where -D is the standard linux wireless extensions driver, wext; -i is the name of wifi card (wlan0, ath0 etc.); and -c is the conf file.)
NOTE: a 10 digit hex password is a 40 bit secure psk; a 26 digit hex password eg "abcdef1234abcdef1234abcdef" is a 120 bit secure psk, and what can be input depends on the security capabilities of the ADSL wifi router/modem
Check yourself - run # wpa_passphrase linksys abcdef1234
and you should get 007aca04beffb195c12dee8a15682053f77f1342713af0d0e87db8141f4cbe86 as part of the output.
#kill -9 pid (pid = process ID, will terminate a locked running process, find via
#ps -aux
Image Mounting
#mount -o loop /share/cruzer.img /mnt/ (mount an image file at /mnt of a pendrive in the same way as an .iso file using the loop function - create initial .img file with #dd if=/dev/sdc1 of=/share/cruzer.img - note that dd requires the device name not the mounted device folder name same as of=/dev/cdrom above)
NETCAT
#netcat -v -w 1 localhost -z 1-3000 (netcat as port scanner - initially found in /etc/alternatives/netcat in Lenny, copy it to /usr/sbin)
g:/nc.exe -lp 1337 > file.zip (nc as ftp receiver on port 1377, pc B, listening)
g:/nc.exe -w 1 x.x.x.x_pc_A 1337 < file.zip (netcat as ftp server now sending on port 1337, pcA to pcB / dir - COOL!!!. Ports close on end file transfer.)
Using pv to give visual progress sending a file, first set listening/receiving pc, #netcat -lp 4444 | pv | > /Efat32/Vids/Ivette.iso
cat /iod/Ivette/Ivette.iso | pv | netcat 10.0.0.1 4444
3.06GB 0:05:49 [9.63MB/s] [ <=> ]
No auto EOF termination using cat (process not closing automatically) for file transfers that are ok up to 7.8GB
Netcat Chat Server
Have you ever needed an improvised one-on-one chat? Netcat can do that too. You simply start listening to connections on some port like this:
#nc.exe -lp 1337 (Then on another machine simply connect to that port:)
#nc.exe x.x.x.x_pcA 1337 (Now start typing on either machine. When you press enter, the line will immediately show up on the other machine)
Netcat Telnet Server
Netcat can also be used to set up a telnet server in a matter of seconds. You can specify the shell (or for that matter any executable) you want netcat to run at a successful connection with the -e parameter:
#nc.exe -lp 1337 -e /bin/bash
On windows you can use:
nc.exe -lp 1337 -e cmd.exe (to run netcat on Vista, run cmd as Admin, cd to netcat dir, and add to anti-virus exceptions at pop up box. Run >nc.exe -lp 1337 etc )
Then on a client machine simply connect to port 1337 and you will get full access to the shell, with the permissions of the user who ran nc.exe on the Win server.
Cloning Hard Drive Partitions Over the Network (umounted partition requigreen to write to remember as dd writes to devices ONLY
dd if=/dev/sda | netcat 192.168.0.1 9000
netcat -l -p 9000 | dd of=/dev/sda
Of course you need to have the cloned partitions unmounted on both systems. So if you are cloning / you will have to boot from a live distro like Knoppix. Note that you can use this technique to clone NTFS partitions as well - just need to use a live Linux distro on both sides.
NTP port 123, SNTP port 583
apt-get install ntp ntpdate (this will enable Net Time Prot sync for pc and will also server other pcs/Cisco. When installed run
# ntpdate-debian to auto setup the local timeservers - EASY! Note the low end Cisco units only run SNTP but will still get time/date from an NTP server: ntp server 131.188.3.223
Partition Expansion
Use gparted from bootable Rescue CD in a GUI
Burn CD/DVD with no GUI software
.#dd if=/name.iso of=/dev/cdrom bs=1M
or with wodim
#wodim /file.iso (this is suficient to burn an iso to default cdrw device, auto found by wodim.
Sparse files are files whose real allocation needs are fulfilled only when data are written inside them. If you try to read from places you haven't written before, you get zeroes - and these zeroes don't really occupy any space in your hard drive. If only one sector of data (512 bytes) gets written at some offset inside a sparse file, then a sector is all the sparse file will reserve from the filesystem - not the size reported by the filesystem!
All that is required to create a 150GB sparse file under Windows is this: (From within a Cygwin command prompt) dd if=/dev/zero of=BigFile bs=1M count=1 seek=150000 This command will execute in 1 second, and it will only reserve 1MB of real hard drive space. Real storage will grow as needed, when data are written inside BigFile.
Great trick to zero a hard drives emty space before zipping its contents as a backup file:
#cat /dev/zero > /zero.fill
This creates an emty file using all the drives remaining space, then delete it.
#rm /zero.fill
gzip / > /other_drive/backup.gzip (or bzip2 etc.)
Compare before and after size with
#du -h /other_drive/backup.gzip
# gpart -W /dev/sdx /dev/sdx (guess partitions and/or backup/re-write lost MBR [the -W switch] back to /dev/sdx after partitions have been guessed correctly - HOPEFULLY!)
host is a simple utility for performing DNS lookups. It is normally
used to convert names to IP addresses and vice versa. When no
arguments or options are given, host prints a short summary of its
command line arguments and options.
black:~# host 127.0.0.1
1.0.0.127.in-addr.arpa domain name pointer Bthomehub.home.
black:~# host bbc.co.uk
bbc.co.uk has address 212.58.224.138
bbc.co.uk mail is handled by 10 cluster1.eu.messagelabs.com.
bbc.co.uk mail is handled by 20 cluster1a.eu.messagelabs.com.
black:~# host 6530b
6530b has address 69.175.20.250
6530b mail is handled by 0 6530b.
black:~# id stevee
uid=1000(stevee) gid=1000(stevee) groups=1000(stevee),6(disk),20(dialout),24(cdrom),25(floppy),29(audio),33(www-data),44(video),46(plugdev),114(sambashare)
#nl /etc/samba/smb.conf
numbers lines in a file and shows contents
#reset (resets terminal init to clear screen, same as
#setterm -reset
# cat > /test.txt
steve (followed by Ctrl-D to close)
# vi /test.txt
steve
# rev /test.txt
evets
#top (shows running processes) q to quit
#wall (writes a msg to all users term windows [but not an Xwindow], end with Ctrl-D, or send file content: # wall < /file.txt)
# tty
#users (shows all currently logged on users, except root session when root is logged in to SuperUserMode Terminal in X, only when in tty1-6 non X)
root stevee
#w (list all logged on users and their processes)
#whereis java (locates the binary, source, and manual page files for a command)
java: /usr/share/java
compaqdeb:~# bing 90.36.72.95 195.92.195.94 (bandwidth measuring app between 2 hosts- note 195.92.195.94 is the DNS of Orange uk and handy to remember for an alternate, and a web access/ping test)
Remove unused services at startup - eg Exim
Services booting are found in /etc/rc*.d and can be prevented from starting by changing their name, and so the link to the binary eg:
# mv -v /etc/rc2.d/S20exim /etc/rc2.d/S_20exim
#last stevee (this filters the contents of /var/log/wtmp since the file was created, eg here filters info on user stevee
# lastlog
Cmd line mail using SendEmail
http://caspian.dotconf.net/menu/Software/SendEmail/
apt-get install sendemail
sendEmail -t stevepedwards@gmail.com -f joeblow@spoofed.com -cc stevepedwards@gmail.com -xu stevepedwards -xp password -s smtp.gmail.com:587
No -m option takes text body from STDIN: firewall:~# sendEmail -f stevepedwards@gmail.com -t stevepedwards@gmail.com -u test -s smtp.gmail.com:587 -xu stevepedwards -xp password -m helo me
Jun 28 23:15:49 firewall sendEmail[1575]: Email was sent successfully!
Or pipe a file into the above eg:
cat /textfile.txt | sendEmail -t stevepedwards@gmail.com -f joeblow@spoofed.com -cc stevepedwards@gmail.com -xu stevepedwards -xp password -s smtp.gmail.com:587
#apt-get install chkconfig
#chkconfig --list | grep '3:on'
#service apache2
Delete All Mail Messages:
#echo 'd *' | mail -N
Delete All Mail Messages: For Any User
#echo 'd *' | mail -N -u username
Another way to use the mail command from the Linux CLI is to get information from a server and email it to yourself or someone else. For instance I may want to review a log file on another computer or have another systems administrator who may or may not have access to the server to view a log file. In the below example we will use the access.log file as an example Apache log that we want to email to ourselves so use the below command to do so.
# more /file.txt | mail user@example.com
#socat SYSTEM:date -
#date
To change the system date use:
# date {mmddhhmiyyyy.ss}
o mm Month
o dd Date
o hh 24 hour format
o mi Minutes
o yyyy Year
o ss seconds
eg: to set system date to Jan 31st 2009, 10:19 p.m, 53 seconds
# date 013122192009.53
To set the time only:
# date +%T -s "22:19:53"
Use hwclock without any parameter, to view the current hardware date and time:
# hwclock
et the hardware date and time based on the system date as shown below:
# hwclock --systohc
# hwclock --systohc --utc
date --date='360 days ago' (can be seconds, minutes, months etc. ago)
Sat Aug 16 20:24:18 CEST 2008
Future dates and Times
$ date --date="1 week" (can be sec, min, hour, day etc.)
Tue Aug 18 20:28:24 CEST 2009
Login to Remote Host using SSH
ssh -v 127.0.0.1 (shows debug info)
To come back to the localhost temporarily, without logging out of remote ssh session, type the escape character (after editing /etc/ssh/ssh_config and removing # from EscapeChar = ~): ~ and ^Z. When back to own console you can see the stopped session by running # jobs
#mount -o loop /share/iomegadeb.img /mnt/
# route
I fixed my "too small", application X font mismatch with HDMI TV resolution by adding this to xorg.conf:
Option "NoDDC"
to Section "Device"
If the above change improves your system, but the result is less than 100% to your satisfaction, you can tweak sizes up or down by making the DisplaySize dimensions slightly larger or smaller than actual.