Lnx Flashcards
Remote command execution
Linux: How to run a command on a remote machine.
Use ssh,
> ssh laeeq@192.168.0.49 ls /tmp > ssh laeeq@192.168.0.49 date
you may have to give absolute path of the command you want to execute.
tcpdump
What is tcpdump command to get traffic to/from port 3000
> tcpdump -i any port 3000
vimdiff
What are vimdiff commands?
- CTL-ww swhitches windows
- do: diff obtain, get difference from other window
- dp: diff put: send difference to other window
- ]c: go to next diff
- [c: go to previous diff
- zo: open zip
- zc: close zip
core file
How to force core file generation from a crashing program.
> ulimit -c unlimited
How to display current resource limits for a user?
> ulimit -a
gdb
How to set a conditional break point in gdb.
b fileName.c:56 if x==50
Dangling symbolic links
What happens when you delete a symbolic link.
The target or actual file remains unaffected.
However, if u delete the target, the symbolic link continues to point to non-existing target file (this called dangling/orphaned symbolic links).
Soft link = Symbolic link
what does the tee
command do?
tee
cmd is used to copy the output of a command to a file.
In addition to displaying normal output of the command, the output is also written to a file.
It is used with pipe symbol
> wc -l prog.c | tee file1.txt
to append to a file instead of overwriting,
> wc -l prog.c | tee -a file1.txt
How is HereDocument used?
When a large amount of textual multiline data is needed as argument to a command, we can use Here Docuement
and provide data inside shell script itself, rather than providing data in a file.
cat << ABCD line 1111 line 222 line 333 ABCD
Pass envirenment variable to a script
How to make a variable available inside a shell script?
> TARGET=x86 ./script.sh
Value of TARGET will be available inside script.sh
Assign values to env variables just before calling the script on the same line.
How to read a variable inside a shell script from keyboard?
Use read
command,
read variableName echo $variableName
What is a common usage of xargs
?
When a command generates a list of files, such as find
command. We can make this file list available to another command like grep
or rm
etc, so that these commands can work on the files list generated by the first command.
Following can be used to delete all header files found by cmd find
> find . -name "*.h" | xargs rm -v
args is normally used after a pipe symbol
Errors in make file recipes
In make file what happens when an error occurs at any time?
Default behaviour: Make program is aborts immediately, no further commands are executed.
If you pre-append minus sign ‘-‘ to any command, error in that command will be ignored and next command will be executed.
If you pre-append ‘@’ to any command, make will not print that command before executing.
What are common automatic variables in makefiles?
- $@ : Name of current target.
- $^ : List of all dependencies
- $< : First dependency in the list of dependencies.
gdb: How to get the sequence of function calls leading to current point of execution?
bt backtrace
Each stack frame will have a number associated with it. Top most stack frame is the most recent one.
gdb: How to get the local variables in current function?
info locals
Command line editing: Go to begining of line.
CTL a
a = begining
Command line editing: Go to end of line.
CTL e
e = end
Command line editing
Command line editing: Delete from curser positionn to the end of line?
CTL k
k = Kill
Command line editing
Command line editing: Clear the whole current line
CTL ak
ak = All Kill
iptables: name three chains
INPUT chain, OUTPUT chain, FORWARD chain
What is an iptables policy?
Each chain has a policy, ACCEPT or DROP.
ACCEPT: Allow all pkts unless a specific rule forbids that kind of pkt.
DROP: Disallow all pkts unless a specific rule allows that kind of pkt.
What are primary and secondary groups in Linux?
Primary group: Has the same name as user name. Created at the time when user is created. Newly created user has membership of this group immediately.
Secondary group: Other groups created separately. Users need to be made members of secondary groups explictly using cmd gpasswd
> gpasswd groupName -a userName
Linux user groups
How to find to which groups a user belongs to?
> groups laeeq > groups # will give info about current user.
You can also use,
~~~
> id laeeq
> id # Lists groups which logged in user is member of
```
You can also read /etc/group file.
Which file contains group information
/etc/group
How to create a new group in Linux?
addgroup newGroupName # Ubuntu etc groupadd newGroupName # Redhat etc
Verify using cat /etc/group
Add a user to a Linux group
How to make user1 a member of group1
Use command gpasswd
gpasswd group1 -a user1
You can also use usermod
command.
Revoke the membership from a group
How to remove a user from a group?
User will no longer have that group’s permissions
gpasswd groupName -d userName
Verify using groups userName
Linux user groups
How to modify a groups details, like change group name etc.
Use command groupmod
Modify group
How is the owner group of a file determined?
Owner group of a file is the primary group of the user who created the file
Linux gropus
What are system
& non-system
of groups in Linux?
There are two kind of groups,
- non-system groups
- system gropus
Non-system groups are used for managing user permissions and access.
System groups are used by system services & daemons to allow system processes to share access to resources, files, directories etc.
non-system group gid is normally greater than 1000.
System group gid is normally less than 1000.
system groups
How to create a system group in Linux?
addgroup newGroupName --system
Normally group id (gid) is less then 1000 for these groups
Linux system users
How to create a system user?
> adduser newUserName --system
- Normally UID of system users is less than 1000.
- They may not have home dir.
- They may not have human login capability.
Linux directory permissions
How to interpret the permissions of a directory as opposed to a file?
as opposed to a permissions of a file.
- read: Ability to list dir contents
- write: Ability to create/delete files in this dir.
- execute: Ability to cd into this dir.
setuid
What is the purpose of setuid on an executable file?
When you set the setuid
on an executable file, then when that file is executed by a non-owner user, the resulting process will still have all permissions of the real owner of that file. Even though the real owner did not run that program.
-rwS
Capital S means, original file did not have execute permission.
lower case s means, original file had execute permission too.
How to set sticky bit on a file?
chmod +t fileName
other’s permission will become –T
Linux groups
How to change the owner group of a file?
Use chgrp
command
> chgrp groupName fileName
Linux groups
How to change the owner group of a file?
Use chgrp
command,
chgrp groupName fileName
C++ scoped enum
What are scoped enums in C++
Define like this,
enum class Fruit { banana, apple, }; Fruit frt; frt = Fruit::apple;
What is the benefit of curly brace initialization of variables, like
~~~
int x{10};
// Rather than,
int x = 10;
// or
int x(10);
~~~
Compiler enforces exact type match.
int x = 5.1; // works int y(6.2); // works // but int z{7.3}; // compilation error
A conversion from floating point to integer is not done at initialization.
Ubuntu packages
How to list all ubuntu packages?
> apt list > apt list --installed
Use grep for specific pkg
How to un-install an ubuntu package?
> apt remove pwgen # Does not remove config files > apt purge pwgen # Removes all config files
How to remove unnecessary dependencies from Ubuntu?
> apt autoremove
How to check if a specific pkg is installed on ubuntu system?
> apt search pwgen
If it is insalled, it will show [installed]
How to autoclean
old downloaded archive files in ubuntu
?
> apt autoclean
How to get information about an ubuntu
package liks pwgen
?
> apt show pwgen
Does not show if a pkg is installed. Use apt list pwgen
for that.
Does each ubuntu release have a codename
?
Yes, use following command,
> lsb_release -a
Examples are jammy
, Bionic Bever
, Focal Fossa
etc.
How to create netcat chat between two computers?
Create listner/server
> nc -l -p 1299 # -l for listen, -p port num
Create netcat client,
> nc 192.168.1.100 1299 # dont use -p on listener
How to check if a port is open on a machine using telnet
> telnet 192.168.1.100 22
- connected to 192.168.1.100 ==> Open
- Trying 192.168.1.100…… ==> Not open
More examples,
> telnet google.com 443
- telnet google.com 443
On Redhat Linux, how do you list package groups
> dnf group list > dnf group list --hidden > dnf group list --installed
How to install Development Tools
in RHEL?
> dnf groupinstall "Development Tools"
In Redhat linux, how to get info about a package group
?
> dnf group info "Development Tools"
How to check the status of network manager?
> systemctl status NetworkManager > nmcli general
Do double tab
after each part to see options available
How to get info about NICs?
> nmcli device status > nmcli device show > nmcli device show eth0 > nmcli connection show > nmcli connection show eth0
How to easily create a new network profile in Linux.
- Go to network settings (Wired)
- Locate the interface name you want to use, press
+
- Add details such as DNS etc.
- To activate new profile, disconnect networking, and connect using new profile.
What are the major components of a connection profile
?
- interface name (eth0, enp3s0)
- profile name (user defined text)
- Type (ethernet, wireless)
- IP4 address
- subnet mask
- Default gateway (gw4)
- DNS addresses
How to create a connection profile using nmcli
command?
> nmcli connection add type ethernet ifname eth0 con-name my_new_conn ip4 192.168.1.111/24 gw4 192.168j.1.1
Specify following parameters,
* connection type (ethernet / radio)
* NIC name (eth0, enp7s0)
* New profile name (my_new_conn)
* ip4 (192.168.1.111/24)
* Default gateway (192.168.1.1)
How to activate an already created connection profile?
> nmcli connection up my_conn_profile_1
How to de-activate an active connection profile?
> nmcli connection down my_conn_profile_1
How do you modify the parameters of a network profile?
e.g., add a DNS address.
> nmcli connection modify my_connection ipv4.dns "8.8.8.8 8.8.4.4" > nmcli connection modify my_connection ipv4.address "192.168.1.100/24" > nmcli connection modify my_connection ipv4.gateway "192.168.1.1"
Take network profile down and up again to take effect.
How to make output of nmcli
cmd more readable?
Use -p pretty
option,
nmcli -p connetion show
Use -p
with all nmcli operations.
How to restrict a network profile usage to a set of users?
> nmcli con mod my_connection connection.permissions mujid > nmcli con mod my_connection connection.permissions user:mujid,farooq
How do you delete a network/connection profile?
> nmcli connection delete my_connection_profile
Use nmcli connection show
to list all known connections/profiles.
While entering nmcli
command, how can you get help while typing?
By pressing TAB twice.
What are some common DNS addresses?
- 75.75.75.75
- 75.75.76.76
- 8.8.8.8
- 8.8.4.4
How to get overall
info about all NIC cards in a Linux system?
> nmcli device status
This is the first command you type.
From here, you can drill down further using nmcli device show eth0
etc.
In nmcli
lingo, what is another name for a profile
?
connection name
or con-name
connection name or profile name is listed as CONNECTION
in last column of ,
nmcli device status
When creating/adding a new connection profile using nmcli
, what are the first three parameters?
con-name, type, ifname
- ifname (an existing NIC name, u can get it by
> mcli device status
) - profile name/connection name: A text name you choose.
- type (ethernet, wifi etc)
> nmcli connection add type ethernet con-name my_new_profile ifname enp3s0
When you create a file using touch
commmand, does it have execute permissions by anybody?
NO
By default, when you create a file, it does not have execute permissions by user, group or others. You can of course give execute permissions later using chmod
command.
What is the role of umask
When you create a file, the bits in umask
are removed from just created file.
E.g., umask=0002 will make sure others
don’t have write permissions to created files.
umask=0333 will make sure that newly created files will have only read permissions by everybody.
How to find current umask
value?
> umask
likely output is 0002, this will remove write permission for others
on newly created files.
How to make umask
equal to 0333
> umask 0333
This will make sure newly created files have only read permissions by everybody. -r–r–r–
How to find what the permissions on a newly created file be, with currently set value of umask
umask -S
How to list all services/units by systemd
> systemctl list-units > systemctl list-units --type=service > systemctl list-units --all > systemctl list-unit-files > systemctl list-unit-files | grep NetworkManager
How to find all journal entries related to a service/unit
> journalctl -u NetworkManager > journalctl -u ssh -f # follow similar to tail -f
How to view a systemd service’s configuration file?
> systemctl cat NetworkManager
cat /etc/systemd/system/NetworkManager.service
How to list dependencies of a systemd service?
systemctl list-dependencies NetowrkManager systemctl list-dependencies --all NetworkManager
How to get low level details about a systemd service?
> systemctl show NetworkManager
After modifying a systemd service, how to reload systemd process to pickup modifications?
> systemctl daemon-reload
What is the basic format of a systemd service file?
cat /etc/systemd/system/test.service [Unit] Description=Example systemd service unit file. [Service] ExecStart=/bin/bash /usr/sbin/example.sh [Install] WantedBy=multi-user.target
What is the equivalent of system V run-levels
in systemd
?
Targets
Where should you keep your service files?
in
/etc/systemd/system
How to list all systemd
targets?
> systemctl list-units --type=target
Name some systemd
targets
- multi-user.target
- network-online.target
- rescue.target
- graphical.target
How to find default systemd
target, that system tries to reach after booting?
> systemctl get-default
How to enforce strict ordering of systemd
service starting?
By using Before
and After
in service file.
wants
and requires
are not strict.
What are the things that systemd
manages?
units
Some unit types are,
- services
- timers
- mounts
How do systemd
timers work?
timer is a kind of unit that systemd manages apart from services.
- You create a unit file
abc.timer
. - Specify periodicity in this file
- You create a service file
abc.service
- You start timer unit
- Now abc.service will be started periodically as per timer period.
timer unit file has same name as service file
How do you create an infinite loop in a bash script?
while true do echo "Test - 1" sleep 1 done
In Linux, how to nicely display an XML file?
> xmllint --format abc.xml
```
How to kill all processes run by a user hamid?
> sudo killall -u hamid
How to create a (normal) user in Linux?
> sudo adduser hamid
You can leave fields like room/phone etc blank.
You can login as this user by doing
> su - hamid
How to create a Linux user and make his login shell rbash
> sudo adduser hamid --shell /bin/rbash
In Linux, how to find user-id and group-id of a user?
> id # gives info about logged in user > id hamid # info about another user
Default values are taken from /etc/adduser.conf
file.
How to remove a Linux user?
Ubuntu
> sudo deluser hamid # home dir wont be deleted > sudo deluser hamid --remove-home > sudo deluser hamid --remove-all-files
Redhat may not have deluser
cmd. Use userdel
> userdel hamid > userdel -r hamid # remove home-dir etc
How to become root user in Linux?
> sudo su -
How to check ACL permissions for a file?
file: youtube/
> getfacl fileName.txt
Typical output
owner: root # group: root user::rwx user:user1:rwx group::r-x mask::rwx other::r-x
How to give ACL permissions “rwx” for user hamid
for a specific file?
> setfacl -m u:hamid:rwx fileName.txt
How do you check if a file has ACL permissions associated with it?
Normal files have only -rwxrwxrwx permissions. But a file with ACL permissions also has a “+” symbo at the end, like -rwxrwxrwx+
How to revoke some ACL permissions for a user or group?
Set new permissions explicitly. For removing write permissions for a user on a file,
> setfacl -m -u:hamid:r-x fileName.txt
How to find details of a Linux
distribution?
> lsb_release -a > ls /etc/*rel* > cat /etc/lsb-release > cat /etc/os-release
What are some systemd
directives to start programs
ExecStart /full/pathname/of/binary ExecStartPost /bin/bash /path/name/script.bash ExecStartPre /bin/bash /fullPath/script.bash ExecStop /bin/bash /full/path/endingScript.sh
- ExecStartPost starts the program immediately after starting the main program. NOT after main program finishes.
When does systemd service directive ExecStop
take effect?
Upon graceful shutdown of servcie.
- When you stop service using
systemctl stop svcName
- When the main program normally finishes
It DOES NOT run when the service crashes due to signal etc.
How can I restart a systemd service after a crash, e.g., when underlying process receives a signal (9).
Use Restart=on-failure
[Unit] Description = A demo service [Service] ExecStart = /bin/bash /path/to/script.bash Restart=on-failure RestartSec=30s # waits of 30 sec before restarting.
Google: Setup self-healing services with systemd
What is the id
of super user
in Linux?
0, zero
uid=0(root) gid=0(root)
Use command id
to get user identifier.
How to delete a group in Linux?
> groupdel groupName
All group names are listed in /etc/group
This file has one line for each group.
That line also contains all users belonging to this group.
In RedHat Linux, what is group wheel
?
In RHEL, wheel
is the name of a group. All members of this group have sudo
capability. If you want to give sudo
capability to any user, just add him to group wheel.
> gpasswd wheel -a hamid # hamid can now do sudo > gpasswd wheel -d hamid # hamid cannot do sudo
In Ubuntu
this kind of group is named sudo
In Redhat Linux, how do you list packages?
> dnf list > dnf list installed > dnf list | grep tmux > dnf list installed | grep tmux
How to find which systemd
units have failed?
> systemctl --failed > systemctl --failed --all
What Linux cmd is used to get info about power sources to the board?
> upower --enumerate > upower -d
How the cmd pstree
works?
> pstree > pstree - u user1 > pstree -p -u hamid # with PIDs
Login with su - hamid
for cleaner outputs.
How are threads shown in pstree
cmd output?
{} means threads of a process
|--2*{thread}
The process has 2 threads running at the momemnt.
How does pstree
show, when a.out
spawns two threads?
pstree -u hamid bash ---a.out---2*{a.out} Default compact format
pstree hamid -c --a.out-------{a.out} | ---{a.out} Non-compact format, each thread in its own line.
pstree hamid -T --a.out-------{a.out} No thread information
How to find parents of a process with pstree
cmd?
Fisrt find PID with pstree hamid -p -c
Then find parents using -s
option
> pstree -s 1234 > pstree -s -p 1234
Don’t use username (hamid) with above cmds
In Linux, how to print all environment variables
?
-
env
cmd gives onlyexported
variables -
set
cmd givesexported
as well asun-exported
variables. -
set
cmd gives more variables. -
env
output is a subset ofset
output
m
How to unset
a variable in bash
?
> unset VarName
How to get the value of a shell variable?
echo $VarName echo ${VarName} # better way
Using curly braces {} is always better
How is alias
cmd used in Linux?
> alias cl=clear > unalias cl # remove alias
How to create exported shell variables for all users in Linux?
Declare them in /etc/environment
file.
How to use CTL R
interactive history?
- Keep pressing
CTL R
to keep going back. - Press left or right arrow key to copy currently displayed cmd to cmd-line. You can edit this cmd now.
- Press
CTL S
to go forward. - If going forward with
CTL S
doesn’t work, typestty -ixon
What are some important shell variables?
- $USER
- $HOME
- $SHELL
- $PWD
*$UID - $HOSTNAME
- $PS1, $PS4
How to get details about a process, given its PID?
> ps -f 1234 > ps -ef # all processes > ps -ef | grep cmdName
How to find the exit status of last command?
Use $?
0 means success, 1 means failure.
Try true
and false
cmds. Then do $?
> true > echo $? # should print 0 > false > echo $? # should print 1
Give some example usages of test
cmd in bash scripts.
test 1 -eq 1 # $? = 0 test 1 -gt 2 # $? = 1 false test 1 -eq 1 -a 2 -gt 1 # -a = AND, -o = OR test -f fileName test -d dirName
Using single or double square brackets is more convenient. [], [[]]
In shell scripts, how to test conditions using single square brackets?
[ 1 -eq 1 ] # $? = 0 [ ! 1 -eq 1 ] # $? = 1 false [ -f fileName ] [ ! -d dirName ] # return 0 if dirName is not a directory
If you use double brackets, you can use ==, >, < instead of -eq, -gt, -lt
In bash scripting, how is double square bracket method different from single square bracket method?
Difference is in condition representation.
With single sqr brkt, you use -eq, -lt, -gt, -a, -o
etc for comparision.
With double sqr brkt, you can use usual algebraic symbols ==, >, < &&, ||
for comparision.
How to check if a user by name hamid
exists in Linux?
Use id
command
> id hamid
How to check if ubuntu
has a specific package installed?
> apt search pwgen
Output should have [installed]
in it.
In ubuntu
where is the info about repositories?
- /etc/apt/sources.list
- /etc/apt/sources.list.d
Each line represents one repository, or package source.
A repository line can be commented out by #
in the begining.
Give an example of arithmatic operation in shell script using double parenthesis.
a=$(( 3 + 5 - 2)) echo $a # 6 a= $(( 2**10)) # 1024
- No floating point arithmetic
- Don’t use $ sign with variables inside double paranthesis.
How is bc
used to perform floating point arithmetic in shell scripts?
echo "1.5 + 2.7" | bc # 4.2 echo "scale=2; 1/3" | bc # .33 a=.5 b=$( echo "$a + 0.3) echo $b #.8