UrFix's Blog

A geek without a cause

Tag: command line

  • You Might remember  my post 25 best Linux commands Think of this as part two. here is another list of really useful commands that you might find handy.

    1) Like top, but for files

    watch -d -n 2 ‘df; ls -FlAt;’

    2) Download an entire website

    wget –random-wait -r -p -e robots=off -U mozilla http://www.example.com

    -p parameter tells wget to include all files, including images.

    -e robots=off you don’t want wget to obey by the robots.txt file

    -U mozilla as your browsers identity.

    –random-wait to let wget chose a random number of seconds to wait, avoid get into black list.

    Other Useful wget Parameters:

    –limit-rate=20k limits the rate at which it downloads files.

    -b continues wget after logging out.

    -o $HOME/wget_log.txt logs the output

    3) List the size (in human readable form) of all sub folders from the current location

    du -h –max-depth=1

    4) A very simple and useful stopwatch

    time read (ctrl-d to stop)

    time read -sn1 (s:silent, n:number of characters. Press any character to stop)

    5) Quick access to the ascii table.

    man ascii

    6) Shutdown a Windows machine from Linux

    net rpc shutdown -I ipAddressOfWindowsPC -U username%password

    This will issue a shutdown command to the Windows machine. username must be an administrator on the Windows machine. Requires samba-common package installed. Other relevant commands are:

    net rpc shutdown -r : reboot the Windows machine

    net rpc abortshutdown : abort shutdown of the Windows machine

    Type:

    net rpc

    to show all relevant commands

    7) Jump to a directory, execute a command and jump back to current dir

    (cd /tmp && ls)

    8) Display the top ten running processes – sorted by memory usage

    ps aux | sort -nk +4 | tail

    ps returns all running processes which are then sorted by the 4th field in numerical order and the top 10 are sent to STDOUT.

    9) List of commands you use most often

    history | awk ‘{a[$2]++}END{for(i in a){print a[i] ” ” i}}’ | sort -rn | head

    10) Reboot machine when everything is hanging (raising a skinny elephant)

    <alt> + <print screen/sys rq> + <R> – <S> – <E> – <I> – <U> – <B>

    If the machine is hanging and the only help would be the power button, this key-combination will help to reboot your machine (more or less) gracefully.

    R – gives back control of the keyboard

    S – issues a sync

    E – sends all processes but init the term singal

    I – sends all processes but init the kill signal

    U – mounts all filesystem ro to prevent a fsck at reboot

    B – reboots the system

    Save your file before trying this out, this will reboot your machine without warning!

    http://en.wikipedia.org/wiki/Magic_SysRq_key

    11) Make ‘less’ behave like ‘tail -f’

    less +F somelogfile

    Using +F will put less in follow mode. This works similar to ‘tail -f’. To stop scrolling, use the interrupt. Then you’ll get the normal benefits of less (scroll, etc.).

    Pressing SHIFT-F will resume the ‘tailling’.

    12) Set audible alarm when an IP address comes online

    ping -i 60 -a IP_address

    Waiting for your server to finish rebooting? Issue the command above and you will hear a beep when it comes online. The -i 60 flag tells ping to wait for 60 seconds between ping, putting less strain on your system. Vary it to your need. The -a flag tells ping to include an audible bell in the output when a package is received (that is, when your server comes online).

    13) Backticks are evil

    echo “The date is: $(date +%D)”
    This is a simple example of using proper command nesting using $() over “. There are a number of advantages of $() over backticks. First, they can be easily nested without escapes:

    program1 $(program2 $(program3 $(program4)))versus

    program1 `program2 \`program3 \`program4\`\``Second, they’re easier to read, then trying to decipher the difference between the backtick and the singlequote: `’. The only drawback $() suffers from is lack of total portability. If your script must be portable to the archaic Bourne shell, or old versions of the C-shell or Korn shell, then backticks are appropriate, otherwise, we should all get into the habit of $(). Your future script maintainers will thank you for producing cleaner code.

    14) Simulate typing

    echo “You can simulate on-screen typing just like in the movies” | pv -qL 10

    This will output the characters at 10 per second.

    15) python smtp server

    python -m smtpd -n -c DebuggingServer localhost:1025

    This command will start a simple SMTP server listening on port 1025 of localhost. This server simply prints to standard output all email headers and the email body.

    16) Watch Network Service Activity in Real-time

    lsof -i

    17) diff two unsorted files without creating temporary files

    diff <(sort file1) <(sort file2)

    bash/ksh subshell redirection (as file descriptors) used as input to diff

    18) Rip audio from a video file.

    mplayer -ao pcm -vo null -vc dummy -dumpaudio -dumpfile <output-file> <input-file>

    replace accordingly

    19) Matrix Style

    tr -c “[:digit:]” ” ” < /dev/urandom | dd cbs=$COLUMNS conv=unblock | GREP_COLOR=”1;32″ grep –color “[^ ]”

    20) This command will show you all the string (plain text) values in ram

    sudo dd if=/dev/mem | cat | strings

    A fun thing to do with ram is actually open it up and take a peek.

    21) Display which distro is installed

    cat /etc/issue

    22) Easily search running processes (alias).

    alias ‘ps?’=’ps ax | grep ‘

    23) Create a script of the last executed command

    echo “!!” > foo.sh

    Sometimes commands are long, but useful, so it’s helpful to be able to make them permanent without having to retype them. An alternative could use the history command, and a cut/sed line that works on your platform.

    history -1 | cut -c 7- > foo.sh

    24) Extract tarball from internet without local saving

    wget -qO – “http://www.tarball.com/tarball.gz” | tar zxvf –

    25) Create a backdoor on a machine to allow remote connection to bash

    nc -vv -l -p 1234 -e /bin/bash

    This will launch a listener on the machine that will wait for a connection on port 1234. When you connect from a remote machine with something like :

    nc 192.168.0.1 1234

    You will have console access to the machine through bash. (becareful with this one)

  • Many Linux newbies love to copy and paste every command they see on the net, curious to find out what they do. Running these following commands won’t kill you, but you’ll wish you were dead. Linux gives full control over the system if you are logged in as root user, running anyone of the following commands without clear understanding of them would lead to a disaster situation.

    dd if=/dev/zero of=/dev/sda formats hard disk back to the factory settings. mkfs.ext3 /dev/sda will format all data from the device specified after the mkfs command. mv ~ /dev/null will erase everything from your root directory.  Basically /dev/null does not exists and anything written to it is actually discarded from the system. dd if=/dev/random of=/dev/port run this command if you are eager to freeze your Linux system. :(){:|:&};: is a forkbomb command, once you run it, it will let you system freeze and you will have no other way except to have it hard reboot ( Please don't run this command if you are feeling curiosity, consequences can be bitter ) rsync -r –delete /home/backup such commands has a delete switch  that can be used to destroy parts of the file system. shutdown -h now shuts your system down and you will have to hard reboot it, don't run this command if you are hosting your servers in any data center or colocation. run shutdown -r now instead. any_command> / dev / sda This command causes total loss of data, in the partition that is mentioned in command http://some_untrusted_source wget-O-| sh Never download untrusted sources and below are implemented, they may be malicious codes find ./ * -exec rm {} \; This removes every file from the current directory on. find . / * -exec rm {} \; This also removes removes every file from the current directory plus every file from the root directory forward! Conclusion I'm sure that are other equally deadly Linux commands that I failed to include here, so if you have something to add, please share it with us via comment.

  • As a Linux user you’ll come to learn and love certain commands. Remembering these commands is the toughest part.

    Some people use cheat-sheets, some create scripts, and some just refer to website for their fix. Here I have posted the 25 top command line snippets. Please remember to always read man pages for any command before running any commands or applications
    25) sshfs name@server:/path/to/folder /path/to/mount/point Mount folder/filesystem through SSH Install SSHFS from http://fuse.sourceforge.net/sshfs.html Will allow you to mount a folder security over a network. 24) !!:gs/foo/bar Runs previous command replacing foo by bar every time that foo appears Very useful for rerunning a long command changing some arguments globally. As opposed to ^foo^bar, which only replaces the first occurrence of foo, this one changes every occurrence. 23) mount | column -t currently mounted filesystems in nice layout Particularly useful if you're mounting different drives, using the following command will allow you to see all the filesystems currently mounted on your computer and their respective specs with the added benefit of nice formatting. 22) <space>command Execute a command without saving it in the history Prepending one or more spaces to your command won't be saved in history. Useful for pr0n or passwords on the commandline. 21) ssh user@host cat /path/to/remotefile | diff /path/to/localfile - Compare a remote file with a local file Useful for checking if there are differences between local and remote files. 20) mount -t tmpfs tmpfs /mnt -o size=1024m Mount a temporary ram partition Makes a partition in ram which is useful if you need a temporary working space as read/write access is fast. Be aware that anything saved in this partition will be gone after your computer is turned off. 19) dig +short txt <keyword>.wp.dg.cx Query Wikipedia via console over DNS Query Wikipedia by issuing a DNS query for a TXT record. The TXT record will also include a short URL to the complete corresponding Wikipedia entry. 18) netstat -tlnp Lists all listening ports together with the PID of the associated process The PID will only be printed if you're holding a root equivalent ID. 17) dd if=/dev/dsp | ssh -c arcfour -C username@host dd of=/dev/dsp output your microphone to a remote computer's speaker This will output the sound from your microphone port to the ssh target computer's speaker port. The sound quality is very bad, so you will hear a lot of hissing. 16) echo "ls -l" | at midnight Execute a command at a given time This is an alternative to cron which allows a one-off task to be scheduled for a certain time. 15) curl -u user:pass -d status="Tweeting from the shell" http://twitter.com/statuses/update.xml Update twitter via curl 14) ssh -N -L2001:localhost:80 somemachine start a tunnel from some machine's port 80 to your local post 2001 now you can acces the website by going to http://localhost:2001/ 13) reset Salvage a borked terminal If you bork your terminal by sending binary data to STDOUT or similar, you can get your terminal back using this command rather than killing and restarting the session. Note that you often won't be able to see the characters as you type them. 12) ffmpeg -f x11grab -s wxga -r 25 -i :0.0 -sameq /tmp/out.mpg Capture video of a linux desktop 11) > file.txt Empty a file For when you want to flush all content from a file without removing it (hat-tip to Marc Kilgus). 10) $ssh-copy-id user@host Copy ssh keys to user@host to enable password-less ssh logins. To generate the keys use the command ssh-keygen 9) ctrl-x e Rapidly invoke an editor to write a long, complex, or tricky command Next time you are using your shell, try typing ctrl-x e (that is holding control key press x and then e). The shell will take what you've written on the command line thus far and paste it into the editor specified by $EDITOR. Then you can edit at leisure using all the powerful macros and commands of vi, emacs, nano, or whatever. 8 ) !whatever:p Check command history, but avoid running it !whatever will search your command history and execute the first command that matches 'whatever'. If you don't feel safe doing this put :p on the end to print without executing. Recommended when running as superuser. 7) mtr google.com mtr, better than traceroute and ping combined mtr combines the functionality of the traceroute and ping programs in a single network diagnostic tool. As mtr starts, it investigates the network connection between the host mtr runs on and HOSTNAME. by sending packets with purposly low TTLs. It continues to send packets with low TTL, noting the response time of the intervening routers. This allows mtr to print the response percentage and response times of the internet route to HOSTNAME. A sudden increase in packetloss or response time is often an indication of a bad (or simply over‐loaded) link. 6 ) cp filename{,.bak} quickly backup or copy a file with bash 5) ^foo^bar Runs previous command but replacing Really useful for when you have a typo in a previous command. Also, arguments default to empty so if you accidentally run: echo "no typozs" you can correct it with ^z 4) cd - change to the previous working directory 3):w !sudo tee % Save a file you edited in vim without the needed permissions I often forget to sudo before editing a file I don't have write permissions on. When you come to save that file and get the infamous "E212: Can't open file for writing", just issue that vim command in order to save the file without the need to save it to a temp file and then copy it back again. 2) python -m SimpleHTTPServer Serve current directory tree at http://$HOSTNAME:8000/ 1) sudo !! Run the last command as root Useful when you forget to use sudo for a command. "!!" grabs the last run command. source That's it people!

Chat

Hi 👋, how can we help?