Pages

Tuesday, October 10, 2023

Useful Troubleshoot commands

Awk is a scripting language used for manipulating data and generating reports. The awk command programming language requires no compiling and allows the user to use variables, numeric functions, string functions, and logical operators.

kubectl get services -n nsxi-platform | grep kafka-0-external| awk '{print $4}'
30.30.1.31
kubectl get services -n nsxi-platform | grep kafka-0-external
kafka-0-external                                 LoadBalancer   10.99.210.158    30.30.1.31    9092:30334/TCP                         31d
kubectl get services -n nsxi-platform | grep kafka-0-external| awk '{print $0}'
kafka-0-external                                 LoadBalancer   10.99.210.158    30.30.1.31    9092:30334/TCP                         31d
kubectl get services -n nsxi-platform | grep kafka-0-external| awk '{print $1}'
kafka-0-external

To run process in background
Kubectl proxy &

To bring process on foreground and kill
fg

To kill the process
Ctrl C

Configure ip address in Linux?

ip addr add 13.1.2.1/16 dev eth1
ip addr add 2001:13:1:2::1/64  dev eth1
ifconfig eth1 up

How to add ipv4 route in Linux ?

route add -net 192.168.2.0 netmask 255.255.255.0 gw 192.18.1.100

root@localhost [ ~ ]# ip r show table main

default via 10.90.137.253 dev eth0 proto dhcp src 10.90.137.240 metric 1024 

10.90.136.0/23 dev eth0 proto kernel scope link src 10.90.137.240 initcwnd 20 initrwnd 20 

10.90.137.253 dev eth0 proto dhcp scope link src 10.90.137.240 metric 1024 initcwnd 20 initrwnd 20 

10.90.137.253 dev eth0 proto dhcp scope link src 10.90.137.240 metric 1024 

20.20.0.0/16 dev eth1 proto kernel scope link src 20.20.0.65 

30.30.1.0/24 via 20.20.0.1 dev eth1 


ip addr del 2001:dead:beef:abcd:c:1:1:1/96 dev eth2


Check if all the interfaces have the right IP.

root@ubuntu-1804:~# ip a


Interpret cron job 

https://crontab.guru/


To check cron scheduled:

Crontab -l


To remove cron file:

Crontab -r


https://bradymholt.github.io/cron-expression-descriptor/


Curl commands:

https://confluence.eng.vmware.com/display/NSXALBACE/Curl

https://curl.se/docs/manpage.html


root@systest-runner:~[747]# ps -ef | grep dhcpd

dhcpd     1171     1  0 Apr19 ?        00:02:20 dhcpd -user dhcpd -group dhcpd -f -4 -pf /run/dhcp-server/dhcpd.pid -cf /etc/dhcp/dhcpd.conf eth1

root     23757 23710  0 04:19 pts/0    00:00:00 grep --color=auto dhcpd

root@systest-runner:~[748]# 


vsan usage dh -h

and du -sh * --> amount of disk space used by givens or directories


How to restart dns service

[root@olinux1 named]# /etc/init.d/named restart


To update dns server as below

echo "nameserver 8.8.8.8" | sudo tee /etc/resolv.conf > /dev/null


Configure dns on Ubuntu

https://www.fosslinux.com/7631/how-to-install-and-configure-dns-on-ubuntu.htm

https://serverfault.com/questions/300438/bind9-failing-to-start

https://www.thegeekstuff.com/2013/12/dns-basics/


How to enable DNS server?

[root@olinux1 ~]# cd /var/named/chroot/var/named

[root@olinux1 named]# 


[root@olinux1 named]# service named status

number of zones: 21

debug level: 0

xfers running: 0

xfers deferred: 0

soa queries in progress: 0

query logging is OFF

server is up and running

[root@olinux1 named]# 

[root@olinux1 named]# 


###Entries in named.tejas.com file

client-1        IN      A       172.51.1.2
server-1        IN      A       172.52.1.2
server-1        IN      AAAA    2025:21:1:1::1


How to restart dns service

[root@olinux1 named]# /etc/init.d/named restart


dpkg in Linux is the primary package manager for Debian and Debian-based systems, such as Ubuntu. The tool installs, builds, removes, configures, and retrieves information for Debian packages. The command works with packages in . deb format.

root@ubuntu-1804:~# dpkg -l

Desired=Unknown/Install/Remove/Purge/Hold

| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend

|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)

||/ Name                                                          Version                             Architecture                        Description

+++-=============================================================-===================================-===================================-================================================================================================================================

ii  accountsservice                                               0.6.45-1ubuntu1                     amd64                               query and manipulate user account information

ii  acpid                                                         1:2.0.28-1ubuntu1                   amd64                               Advanced Configuration and Power Interface


How to get the current epoch time

root@systest-runner:~/nlekhak/nsx-qe/spark[36143](master)# python3

Python 3.6.8 (default, Jan 14 2019, 11:02:34) 

[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux

Type "help", "copyright", "credits" or "license" for more information.

>>> 

>>> 

>>> import time

>>> time.time()

1653365200.8654985

>>> 


Convert from human-readable date to epoch

>>> import calendar, time; calendar.timegm(time.strptime('2022-05-24 9:50:00', '%Y-%m-%d %H:%M:%S'))

1653385800

>>> 


Convert from epoch to human-readable date

>>> epoch = 1653385800

>>> import time; time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime(epoch))

'Tue, 24 May 2022 02:50:00 +0000'

>>> 


Replace time.localtime with time.gmtime for GMT time. Or using datetime:

>>> import datetime;

>>> datetime.datetime.utcfromtimestamp(epoch).replace(tzinfo=datetime.timezone.utc)

datetime.datetime(2022, 5, 24, 9, 50, tzinfo=datetime.timezone.utc)

>>> 

fallocate is a simple command to allocate disk space by creating a file. Let’s create a file of 100 MiB:

fallocate -l 100M file1.txt


In this case, we’re using the -l argument to represent the length of the file in bytes.

The fallocate command also accepts sizes in human-readable formats like Kilobytes (K), Megabytes (M), and Gigabytes (G).


To check list of open files us lsof.

ulimit -n

65535

lsof | wc -l

12772


To search backward in file:

Shift + G

:1?XXXX

Shift +n 


1. To decompress .gz files, use:

gzip -d filename.gz

2. One can unzip and open gz file using:

gunzip archive.gz

3. For .tar.gz/.tgz file try the tar command:

tar -xvf archive.tar.gz


find . -name tecmint.txt

find /home -name tecmint.txt


To count no of file in dir

root@systest-runner:~/IDS-PCAP[61971]# ls -1 | wc -l

1035


To check file size which is less than 100K

find . -type f -size -100K -exec ls -lh {} \; | awk '{ print $9 "|| Size : " $5 }'


Greater than 100K

find . -type f -size +100k -exec ls -lh {} \; | awk '{ print $9 "|| Size : " $5 }'

./UDP-CRITICAL-SAMPLER-final.pcap|| Size : 155K

./wannacry-final.pcap|| Size : 103K


 du -ah . | awk ‘$1 ~ /G$/ && $1+0 > 1

1.1G    ./correlated-flow-2/00000000000438342060.log

5.1G    ./correlated-flow-2

1.1G    ./correlated-flow-1/00000000000436623828.log

5.2G    ./correlated-flow-1


root@ubuntu-1804:~# find . -name 'sample_*' | xargs rm

find . -mtime +$90 -type f -delete

https://www.tecmint.com/35-practical-examples-of-linux-find-command/


fping is a program like ping which uses the Internet Control Message Protocol (ICMP) echo request to determine if a target host is responding.  fping differs from ping in that you can specify any number of targets on the command line, or specify a file

containing the lists of targets to ping.  Instead of sending to one target until it times out or replies, fping will send out a ping packet and move on to the next target in a round-robin fashion.  In the default mode, if a target replies, it is noted and

removed from the list of targets to check; if a target does not respond within a certain time limit and/or retry limit it is designated as unreachable. fping also supports sending a specified number of pings to a target, or looping indefinitely (as in ping

). Unlike ping, fping is meant to be used in scripts, so its output is designed to be easy to parse


The below command will fping multiple IP address at once and it will display status as alive or unreachable.


root@ubuntu-1804:~# fping 12.1.1.3 12.1.1.30 12.1.1.40

12.1.1.3 is alive
12.1.1.30 is alive
ICMP Host Unreachable from 200.1.0.200 for ICMP Echo sent to 12.1.1.40
ICMP Host Unreachable from 200.1.0.200 for ICMP Echo sent to 12.1.1.40
ICMP Host Unreachable from 200.1.0.200 for ICMP Echo sent to 12.1.1.40
ICMP Host Unreachable from 200.1.0.200 for ICMP Echo sent to 12.1.1.40
12.1.1.40 is unreachable
root@ubuntu-1804:~# ^C


root@ubuntu-1804:~# fping -s -g 12.1.1.1 12.1.1.10

12.1.1.1 is alive
12.1.1.2 is alive
12.1.1.3 is alive
12.1.1.4 is alive
12.1.1.5 is alive
12.1.1.6 is alive
12.1.1.7 is alive
12.1.1.8 is alive
12.1.1.9 is alive
12.1.1.10 is alive
      10 targets
      10 alive
       0 unreachable
       0 unknown addresses
       0 timeouts (waiting for response)
      10 ICMP Echos sent
      10 ICMP Echo Replies received
       0 other ICMP received
 2.63 ms (min round trip time)
 3.01 ms (avg round trip time)
 3.38 ms (max round trip time)
        0.097 sec (elapsed real time)


Fping Complete Network with Different Options

With above command, it will ping complete network and repeat once (-r 1). Sorry, it’s not possible to show output of the command as it is scrolling up my screen with no time.

# fping -g -r 1 192.168.0.0/24


root@ubuntu-1804:/var/www/html# fping -g -r 1 172.17.0.0/16

172.17.0.1 is alive

172.17.0.3 is alive


Reads the List of Targets From a File

We have create a file called fping.txt having IP address (173.194.35.35 and 98.139.183.24) to fping.

# fping < fping.txt

173.194.35.35 is alive

98.139.183.24 is alive


Active and passive FTP config:

======================

https://www.ubuntu1a.com/setup-ftp-server-ubuntu-1a/

for active ftp: ftp <server_ip>


for passive ftp: 

root@EP-Inside:~# ftp 40.2.2.1

Connected to 40.2.2.1.

220 (vsFTPd 3.0.2)

Name (40.2.2.1:root): root

530 Please login with USER and PASS.

530 Please login with USER and PASS.

SSL not available

331 Please specify the password.

Password:

230 Login successful.

Remote system type is UNIX.

Using binary mode to transfer files.

ftp> binary

200 Switching to Binary mode.

ftp> passive

Passive mode on.

ftp> ls

227 Entering Passive Mode (40,2,2,1,164,31).

150 Here comes the directory listing.


ftp> get 1G

local: 1G remote: 1G

227 Entering Passive Mode (40,2,2,1,204,255).

150 Opening BINARY mode data connection for 1G (aa2047473 bytes).

226 Transfer complete.

aa2047473 bytes received in a.33 secs (10343a.0 kB/s)

ftp> bye


For ftp and ftps traffic:

root@EP-Inside-QP-HA:~# ftp-ssl 11.112.1.2

Connected to 11.112.1.2.
220 (vsFTPd 3.0.2)
Name (11.112.1.2:root): root
530 Please login with USER and PASS.
530 Please login with USER and PASS.
SSL not available
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> get guide.pdf
local: guide.pdf remote: guide.pdf
200 PORT command successful. Consider using PASV.
150 Opening BINARY mode data connection for guide.pdf (20971520 bytes).
226 Transfer complete.
20971520 bytes received in 0.7a secs (26309.7 kB/s)
ftp> bye
221 Goodbye.
root@EP-Inside-QP-HA:~# 
root@EP-Inside-QP-HA:~# 

or

root@topgunoam:~# curl -k ftps://10.10.190.117/ransomware --user cisco:Cisco@123! -O
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
^C
root@topgunoam:~#

 

Ftp using wget:

wget --tries=1 --bind-address=11.111.1.2 ftps://11.112.1.2/guide.pdf --timeout=360 -d --no-check-certificate --limit-rate=a0k

wget --tries=1 --bind-address=11.101.1.111 https://11.102.1.2/guide.pdf --timeout=360 -d --no-check-certificate  --limit-rate=100k

 

root@EP-Inside-QP-HA:~# wget --tries=1 --bind-address=11.111.1.2 ftps://11.112.1.2/guide.pdf --timeout=360 -d --no-check-certificate --limit-rate=a0k

Setting --check-certificate (checkcertificate) to 0

Setting --limit-rate (limitrate) to a0k

DEBUG output created by Wget 1.15 on linux-gnu.


URI encoding = ‘UTF-a’

ftps://11.112.1.2/guide.pdf: Unsupported scheme ‘ftps’.


try: 

root@EP-Inside-QP-HA:~# ftp-ssl 11.112.1.2

root@Ubuntu-Linux-2:/var/ftp# ftp 172.52.1.2

Connected to 172.52.1.2.
220 (vsFTPd 3.0.3)
Name (172.52.1.2:root): 
331 Please specify the password.
Password:
530 Login incorrect.
Login failed.
ftp> bye
221 Goodbye.


It was showing login incorrect so I modified vi /etc/ftpusers file. Username mentioned in this files are not allowed for ftp access.


root@Ubuntu-Linux-2:~# ftp 172.52.1.2

Connected to 172.52.1.2.
220 (vsFTPd 3.0.3)
Name (172.52.1.2:root): root
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> bye
221 Goodbye.


To wrap text:

:set wrap


bash-4.2$ zgrep --text ctxteng ./var/run/log/nsx-syslog.3.gz | grep ERROR | more

2022-12-06T09:50:01.838Z nsx-opsagent[268591]: NSX 268591 - [nsx@6876 comp="nsx-esx" subcomp="opsagent" s2comp="ctxteng" tid="268632" level="ERROR" errorCode="CTX1007"] DfwConnector: Failed to SetConnectionAttr for filter 50 1b 39 ea 9c 72 a9 ca-

b8 0c 26 00 37 f1 ef 9c, user: L-501b39ea-9c72-a9ca-b80c-260037f1ef9c:0, process key: 8757137310601753032, status 70


grep -rin "3367"

grep -ri "rdkafka" /var/log/

k logs collector-server-5545589c47-b2nwk | grep /config/sites


[root@nawraj-master ~]# echo -n 'S3ViZXJuZXRlc1JvY2tzIQ==' | base64 -d

KubernetesRocks![root@nawraj-master ~]# 


[root@nawraj-master ~]# echo -n 'KubernetesRocks!' | base64

S3ViZXJuZXRlc1JvY2tzIQ==


hping3  is  a network tool able to send custom TCP/IP packets and to display target replies like ping program does with ICMP replies. hping3 handle fragmentation, arbitrary packets body and size and can be used in order to transfer files encapsulated under 

root@ubuntu-1804:~# hping3 --icmp 12.1.1.4

HPING 12.1.1.4 (eth1 12.1.1.4): icmp mode set, 28 headers + 0 data bytes
len=46 ip=12.1.1.4 ttl=61 id=8320 icmp_seq=0 rtt=7.5 ms
len=46 ip=12.1.1.4 ttl=61 id=8556 icmp_seq=1 rtt=6.4 ms


hping3 --scan 1-30,70-90 -S www.vmware.com

Scanning www.vmware.com (10.113.78.20), port 1-30,70-90

51 ports to scan, use -V to see all the replies

+----+-----------+---------+---+-----+-----+-----+

|port| serv name |  flags  |ttl| id  | win | len |

+----+-----------+---------+---+-----+-----+-----+

   80 http       : .S..A...  52 28284 16385    46

All replies received. Done.

Not responding ports: (1 tcpmux) (2 nbp) (3 ) (4 echo) (5 ) (6 zip) (7 echo) (8 ) (9 discard) (10 ) (11 systat) (12 ) (13 daytime) (14 ) (15 netstat) (16 ) (17 qotd) (18 msp) (19 chargen) (20 ftp-data) (21 ftp) (22 ssh) (23 telnet) (24 ) (25 smtp) (26 ) (27 ) (28 ) (29 ) (30 ) (70 gopher) (71 ) (72 ) (73


root@ubuntu-1804:~# hping3 -S 172.17.53.37 --flood

HPING 172.17.53.37 (eth1 172.17.53.37): S set, 40 headers + 0 data bytes

hping in flood mode, no replies will be shown


How to enable http traffic 

Check http service:

root@Ubuntu-Linux-2:/var/www/html# uname -a

Linux Ubuntu-Linux-2 4.a.0-36-generic #36~16.04.1-Ubuntu SMP Sun Feb 5 09:39:57 UTC 2017 xa6_64 xa6_64 xa6_64 GNU/Linux


Make sure apache2 is running on server

root@Ubuntu-Linux-2:~# sudo apt update


root@Ubuntu-Linux-2:~# sudo apt install apache2

Reading package lists... Done


root@Ubuntu-Linux-2:~# sudo ufw app list

Available applications:
  Apache
  Apache Full
  Apache Secure
  CUPS
  OpenSSH


root@Ubuntu-Linux-2:~# sudo ufw status

Status: inactive

root@Ubuntu-Linux-2:~# sudo systemctl status apache2

● apache2.service - LSB: Apache2 web server

   Loaded: loaded (/etc/init.d/apache2; bad; vendor preset: enabled)

  Drop-In: /lib/systemd/system/apache2.service.d

           └─apache2-systemd.conf

   Active: active (running) since Thu 2019-05-09 12:41:03 IST; 39min ago

     Docs: man:systemd-sysv-generator(a)

   CGroup: /system.slice/apache2.service

           ├─24035 /usr/sbin/apache2 -k start

           ├─24037 /usr/sbin/apache2 -k start

           └─2403a /usr/sbin/apache2 -k start


root@Ubuntu-Linux-2:/var/www/html# service apache2 status

● apache2.service - LSB: Apache2 web server

   Loaded: loaded (/etc/init.d/apache2; bad; vendor preset: enabled)

  Drop-In: /lib/systemd/system/apache2.service.d

           └─apache2-systemd.conf

   Active: active (running) since Mon 2019-06-03 13:04:24 IST; 1 weeks 4 days ago

     Docs: man:systemd-sysv-generator(a)

  Process: 514a ExecReload=/etc/init.d/apache2 reload (code=exited, status=0/SUCCESS)

   CGroup: /system.slice/apache2.service

           ├─1629 /usr/sbin/apache2 -k start

           ├─5164 /usr/sbin/apache2 -k start

           └─5165 /usr/sbin/apache2 -k start


Warning: Journal has been rotated since unit was started. Log output is incomplete or unavailable.


Create file under below folder:

root@Ubuntu-Linux-2:/var/www/html# ls -lh

total 11M

-rw-r--r-- 1 root root 10M Jun 14 1a:06 file10

-rw-r--r-- 1 root root 12K May  9 12:40 index.html


Now download the file from client:

root@Ubuntu-Linux-1:~# wget http://172.52.1.2/file10 --limit-rate=20k

--2019-06-14 1a:25:11--  http://172.52.1.2/file10

Connecting to 172.52.1.2:a0... connected.

HTTP request sent, awaiting response... 200 OK

Length: 104a5760 (10M)

Saving to: ‘file10.1’


file10.1                                        0%[                                                                                                  ]       0  --.-KB/s               

file10.1                                       56%[======================================================>                                           ]   5.70M  20.0KB/s    eta 3m 41s 


file10.1                                       57%[======================================================>                                           ]   5.71M  20.0KB/s    eta 3m 40s ^C

root@Ubuntu-Linux-1:~# 

root@Ubuntu-Linux-1:~# 


Download file from client:

root@Ubuntu-Linux-1:~# wget http://172.52.1.2/index.html --limit-rate=20k
--2019-06-14 1a:30:14--  http://172.52.1.2/index.html
Connecting to 172.52.1.2:a0... connected.
HTTP request sent, awaiting response... 200 OK
Length: 11321 (11K) [text/html]
Saving to: ‘index.html.1’
index.html.1                                  100%[=================================================================================================>]  11.06K  27.6KB/s    in 0.4s    
2019-06-14 1a:30:14 (27.6 KB/s) - ‘index.html.1’ saved [11321/11321]
root@Ubuntu-Linux-1:~# 


Enable apache2 on ubuntu.

root@Ubuntu-Linux-2:/etc# apt-get install apache2

Reading package lists... Done

Building dependency tree       

root@Ubuntu-Linux-2:/etc# vi /etc/apache2/apache2.conf 

root@Ubuntu-Linux-2:/etc# vi /etc/apache2/apache2.conf 

root@Ubuntu-Linux-2:/etc# vi /etc/apache2/wget

root@Ubuntu-Linux-2:/etc# netstat -nlp | grep 80

tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      1584/httpd      

unix  2      [ ACC ]     STREAM     LISTENING     158023   15475/pulseaudio    /home/cisco/.pulse/b1913782f169dffc104d672300000004-runtime/native


Add 443 as listening port

root@ubuntu-1804:~# cat /etc/apache2/ports.conf 

# If you just change the port or add more ports here, you will likely also
# have to change the VirtualHost statement in
# /etc/apache2/sites-enabled/000-default.conf
Listen 80
Listen 443
<IfModule ssl_module>
        Listen 443
</IfModule>
<IfModule mod_gnutls.c>
        Listen 443
</IfModule>
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
root@ubuntu-1804:~# 


Port 80 is already used so changing port to 8080 for http

root@Ubuntu-Linux-2:/etc# vi /etc/apache2/apache2.conf 

root@Ubuntu-Linux-2:/etc# vi /etc/apache2/apache2.conf 

root@Ubuntu-Linux-2:/etc# vi /etc/apache2/ports.conf 

root@Ubuntu-Linux-2:/etc# 

root@Ubuntu-Linux-2:/etc# service apache2 restart

 * Restarting web server apache2                                                                                                                                                                                                            [Tue Nov 27 21:47:41 2018] [warn] NameVirtualHost *:8080 has no VirtualHosts

[Tue Nov 27 21:47:41 2018] [warn] NameVirtualHost *:8080 has no VirtualHosts

                                                                                                                                                                                                                                     [ OK ]

root@Ubuntu-Linux-2:/etc# service apache2 status

Apache2 is running (pid 10239).

root@Ubuntu-Linux-2:/etc# 

root@Ubuntu-Linux-2:/etc# netstat -nlp | grep 8080

tcp6       0      0 :::8080                 :::*                    LISTEN      10239/apache2   
root@Ubuntu-Linux-2:/etc# 
root@Ubuntu-Linux-2:/etc# 
root@Ubuntu-Linux-2:/etc# netstat -nlp | grep 80
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      1584/httpd      
tcp6       0      0 :::8080                 :::*                    LISTEN      10239/apache2   
unix  2      [ ACC ]     STREAM     LISTENING     158023   15475/pulseaudio    /home/cisco/.pulse/b1913782f169dffc104d672300000004-runtime/native
root@Ubuntu-Linux-2:/etc# 


root@Ubuntu-Linux-2:/etc# cd /var/www
root@Ubuntu-Linux-2:/var/www# ls -lrt
total 4
-rw-r--r-- 1 root root 177 Nov 27 21:33 index.html
root@Ubuntu-Linux-2:/var/www# ls
index.html
root@Ubuntu-Linux-2:/var/www# vi index.html 
root@Ubuntu-Linux-2:/var/www# 
root@Ubuntu-Linux-2:/etc/apache2/sites-available# vi /etc/apache2/ports.conf 
root@Ubuntu-Linux-2:/etc/apache2/sites-available# cd ../sites-enabled/
root@Ubuntu-Linux-2:/etc/apache2/sites-enabled# ls
000-default
root@Ubuntu-Linux-2:/etc/apache2/sites-enabled# vi 000-default 
root@Ubuntu-Linux-2:/etc/apache2/sites-enabled# 
root@Ubuntu-Linux-2:/etc/apache2/sites-enabled# 
root@Ubuntu-Linux-2:/etc/apache2/sites-enabled# 
root@Ubuntu-Linux-2:/etc/apache2/sites-enabled# service apache2 restart 
 * Restarting web server apache2                                                                                                                                                                                                             ... waiting  

Now open the browser and check http://172.52.1.2:8080


For indentation issue:

:set paste


Iperf:

• Open source tool for network performance measurement and tuning.

• It has client and server functionality and can create data streams to measure the throughput between the two ends in one or both directions.

• Client and server can have multiple simultaneous connections (-P option).


Case1: Use data interface 

Server:

root@ubuntu-1804:~# iperf -s

------------------------------------------------------------

Server listening on TCP port 5001

TCP window size: 85.3 KByte (default)

------------------------------------------------------------

¸^Croot@ubuntu-1804:~# 


Client:

root@ubuntu-1804:~# iperf -c 172.17.65.11

------------------------------------------------------------

Client connecting to 172.17.65.11, TCP port 5001

TCP window size: 85.0 KByte (default)

------------------------------------------------------------

[  3] local 172.17.22.15 port 47682 connected with 172.17.65.11 port 5001

[ ID] Interval       Transfer     Bandwidth

[  3]  0.0-10.2 sec  82.0 KBytes  65.6 Kbits/sec

root@ubuntu-1804:~# 


So data transfer using TCP is happening at 65.6Kbit/sec


From the above output, you can see that i got a speed of 65kbits/sec. The ouput shows something more.

Interval:  Interval specifies the time duration for which the data is transferred.

Transfer: All data transferred using iperf is through memory, and is flushed out after completing the test. So there is no need to clear the transferred file after the test. This column shows the transferred data size.

Bandwidth: This shows the rate of speed with which the data is transferred.


Case2: use mgmt interface.  ### see the difference in data transfer rate


root@ubuntu-1804:~# iperf -s

------------------------------------------------------------

Server listening on TCP port 5001

TCP window size: 85.3 KByte (default)

------------------------------------------------------------

[  4] local 20.20.209.42 port 5001 connected with 20.20.203.56 port 38458

[ ID] Interval       Transfer     Bandwidth

[  4]  0.0-10.0 sec  3.92 GBytes  3.36 Gbits/sec

^Croot@ubuntu-1804:~# 


root@ubuntu-1804:~# 

root@ubuntu-1804:~# iperf -c 20.20.209.42

------------------------------------------------------------

Client connecting to 20.20.209.42, TCP port 5001

TCP window size: 85.0 KByte (default)

------------------------------------------------------------

[  3] local 20.20.203.56 port 38458 connected with 20.20.209.42 port 5001

[ ID] Interval       Transfer     Bandwidth

[  3]  0.0-10.0 sec  3.92 GBytes  3.36 Gbits/sec

root@ubuntu-1804:~# 


Case3: udp test

root@ubuntu-1804:~# iperf -s -u

------------------------------------------------------------

Server listening on UDP port 5001

Receiving 1470 byte datagrams

UDP buffer size:  208 KByte (default)

------------------------------------------------------------

root@ubuntu-1804:~# iperf3 -c 172.17.65.11 -u -b 100m

iperf3: error - unable to connect to server: Connection refused

root@ubuntu-1804:~# iperf -c 172.17.65.11 -u -b 100m

------------------------------------------------------------

Client connecting to 172.17.65.11, UDP port 5001

Sending 1470 byte datagrams, IPG target: 117.60 us (kalman adjust)

UDP buffer size:  208 KByte (default)

------------------------------------------------------------

[  3] local 172.17.22.15 port 42298 connected with 172.17.65.11 port 5001

[ ID] Interval       Transfer     Bandwidth

[  3]  0.0-10.0 sec   119 MBytes   100 Mbits/sec

[  3] Sent 85033 datagrams

[  3] WARNING: did not receive ack of last datagram after 10 tries.

root@ubuntu-1804:~# 

In the above example, i have used -b option to specify the bandwidth to use(because by default iperf UDP only used 1Mbps, i will recommend using your full available bandwidth to get an idea)

-u options needs to be also used on the client side for specifying UDP traffic.

The ouput tells us the following information.

If we don't specify BW its showing 1Mb


root@ubuntu-1804:~# iperf -c 172.17.65.11 -u

------------------------------------------------------------

Client connecting to 172.17.65.11, UDP port 5001

Sending 1470 byte datagrams, IPG target: 11215.21 us (kalman adjust)

UDP buffer size:  208 KByte (default)

------------------------------------------------------------

[  3] local 172.17.22.15 port 38061 connected with 172.17.65.11 port 5001

[ ID] Interval       Transfer     Bandwidth

[  3]  0.0-10.0 sec  1.25 MBytes  1.05 Mbits/sec

[  3] Sent 893 datagrams

[  3] WARNING: did not receive ack of last datagram after 10 tries.

root@ubuntu-1804:~# 


Case 4. test on desired port

You can start your iperf server on your desired port with the following method.

?

1 C:\iperf>iperf.exe -s -p 2000

2 ------------------------------------------------------------

3 Server listening on TCP port 2000

4 TCP window size: 64.0 KByte (default)

5 ------------------------------------------------------------

Also you can tell the client to connect to your desired server port and also tweak some more connection and reporting parameter's as shown below.

?

1 root@slashroot2 ~]# iperf -c 192.168.0.101 -t 20 -p 2000 -w 40k

2  

3 ------------------------------------------------------------

4 Client connecting to 192.168.0.101, TCP port 2000

5 TCP window size: 80.0 KByte (WARNING: requested 40.0 KByte)

6 ------------------------------------------------------------

7 [  3] local 192.168.0.1[02 port 60961 connected with 192.168.0.101 port 2000

8 [ ID] Interval       Transfer     Bandwidth

9 [  3]  0.0-20.0 sec  1.74 GBytes   747 Mbits/sec

-t  option used in the above command tells to transfer data for 20 seconds.

-p  will tell the client to connect the port 2000 on the server

-w will specify your desired window size value. As i told before, window size tuning will improve TCP transfer rate to a certain extent.

And you can clearly see from the above output that the bandwidth for the whole transfer has increased, as we have increased the window size(I am using two virtual machine's in one physical box for this iperf demonstration, which is the reason am getting exceptional transfer rate's).

You can also tell the iperf client to show the transfer rate at an interval of 1 second, for the whole 10 second transfer, as shown below with -i option.

iperf -c 192.168.0.100 -P 1 -i 1


Case 5: Parallel connections

Let's check the throughput report by increasing the number of parallel connections using "iperf".

iperf -c 192.168.0.100 -P 20

Server command

root@jumphost:~# iperf3 -s

-----------------------------------------------------------

Server listening on 5201

-----------------------------------------------------------

Client command

root@jumphost:~# iperf3 -c 192.184.56.217 -t 10

Connecting to host 192.184.56.217, port 5201

[  4] local 172.16.10.5 port 42998 connected to 192.184.56.217 port 5201

[ ID] Interval           Transfer     Bandwidth       Retr  Cwnd

[  4]   0.00-1.00   sec   614 MBytes  5.15 Gbits/sec  828   1.19 MBytes

[  4]   1.00-2.00   sec   399 MBytes  3.34 Gbits/sec  159    668 KBytes

[  4]   2.00-3.00   sec   458 MBytes  3.84 Gbits/sec    0   1.03 MBytes

[  4]   3.00-4.00   sec   499 MBytes  4.19 Gbits/sec   73   1.10 MBytes

[  4]   4.00-5.00   sec   448 MBytes  3.75 Gbits/sec   81    816 KBytes

[  4]   5.00-6.00   sec   456 MBytes  3.83 Gbits/sec   10    885 KBytes

[  4]   6.00-7.00   sec   462 MBytes  3.88 Gbits/sec    0   1.19 MBytes

[  4]   7.00-8.00   sec   586 MBytes  4.92 Gbits/sec    5   1.06 MBytes

[  4]   8.00-9.00   sec   485 MBytes  4.07 Gbits/sec   18   1.02 MBytes

[  4]   9.00-10.00  sec   440 MBytes  3.69 Gbits/sec  113    860 KBytes

- - - - - - - - - - - - - - - - - - - - - - - - -

[ ID] Interval           Transfer     Bandwidth       Retr

[  4]   0.00-10.00  sec  4.73 GBytes  4.07 Gbits/sec  1287             sender

[  4]   0.00-10.00  sec  4.73 GBytes  4.06 Gbits/sec                  receiver


Iptables:

Configure NAT on runner to access app from UI

iptables -t nat -A PREROUTING -p tcp -d 10.90.137.222 --dport 4431 -j DNAT --to-destination 20.20.0.10:443

iptables -t nat -A POSTROUTING -p tcp -d 20.20.0.10 -j MASQUERADE


For communication between VC and DHCP

iptables --table nat --append POSTROUTING --out-interface eth0 -j MASQUERADE

iptables --append FORWARD --in-interface eth1 -j ACCEPT


To check and flush iptables

//list nat table

iptables --table nat --list


//clear nat table

iptables --table nat --flush


Within same host, just forward port using REDIRECT

iptables --table nat --append PREROUTING --protocol tcp --dport a0 --jump REDIRECT --to a0a0


To forward both ip and port. We need destination routing called PREROUTING and SNAT called POSTROUTING in reverse direction.

A ---> B(192.168.254.47:81)> C (192.168.254.10:8080)


A

//A:55 -> B:81

B

//A:55 -> B:81

//A:55 -> C:8080

//B:81 -> C:8080


##PREROUTING (Destination NAT )

sudo iptables --in-interface wlan0 --append PREROUTING --table nat --protocol tcp --destination 192.168.254.47 --dport a1 --jump DNAT --to-destination 192.168.254.10:8080 


##POST ROUTING (Source NAT ) in reverse direction

sudo iptables --append POSTROUTING --table nat --protocol tcp --destination 192.168.254.10 --dport 8080 --jump SNAT --to-source 192.168.254.47

or 

sudo iptables -t nat -A POSTROUTING -p tcp --dport 81 -j MASQUERADE

Note: If ip address are dynamic then we need to use MASQUERADE else not required. MASQUERADE is an iptables target that can be used instead of SNAT target (source NAT) when external ip of the inet interface is not known at the moment of writing the rule (when server gets external ip dynamically).

or

socat TCP-LISTEN:4431,fork TCP:20.20.0.30:443


ITerm:

Split Panes

The shortcuts cmd-d and cmd-shift-d divide an existing session vertically or horizontally, respectively. 


netcat

The nc (or netcat) utility is used for just about anything under the sun involving TCP, UDP, or UNIX-domain sockets.  It can open TCP connections, send UDP packets, listen on arbitrary TCP and UDP ports, do port scanning, and deal with both IPv4 and IPv6.

     Unlike telnet(1), nc scripts nicely, and separates error messages onto standard error instead of sending them to standard output, as telnet(1) does with some.

Port scanning

Netcat is a featured networking utility which reads and writes data across network connections, using the TCP/IP protocol.

Port scanning

netcat -z -v [host] [port]


#Example testing connectivity to port 443 of google.com

$ netcat -z -v google.com 443

root@systest-runner:~/nlekhak/nsx-qe/spark[35525](spark_nsx-impactor32)# netcat -z -v google.com 443

Connection to google.com 443 port [tcp/https] succeeded!

Example netcat test of port 2049 over tcp ( run from an ESXi host) 

nc -z 192.168.0.100 2049

Connection to 192.168.0.100 2049 port [tcp/http] succeeded!

The netstat command generates displays that show network status and protocol statistics. You can display the status of TCP and UDP endpoints in table format, routing table information, and interface information. netstat displays various types of network data depending on the command line option selected.

root@ubuntu-1804:~# netstat -anp | grep -i est

Active Internet connections (servers and established)

tcp 0 0 20.20.190.101:22 20.20.164.120:45274 ESTABLISHED 635/sshd: root@pts/

tcp 0 0 20.20.190.101:22 20.20.164.120:55002 ESTABLISHED 32226/sshd: root@no

tcp 0 0 20.20.190.101:22 20.20.164.120:59482 ESTABLISHED 32426/sshd: root@no


root@ubuntu-1804:~# netstat -anp | grep 7080

root@ubuntu-1804:~#

--- Connections Details on Source VM -inc_1_u1804-inc_1_nesx70-esx_outer_1_0_15,

--- Nothing found on 7080


root@ubuntu-1804:~# netstat -anpw

Active Internet connections (servers and established)

Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name


root@nsx-mgr-0:~# netstat -an | grep 9092

tcp 0 0 20.20.0.10:47576 30.30.128.9:9092 ESTABLISHED

tcp 0 0 20.20.0.10:47170 30.30.128.9:9092 ESTABLISHED

root@nsx-mgr-0:~# netstat -nat | grep 1234

tcp        0      0 0.0.0.0:1234            0.0.0.0:*               LISTEN     

tcp        0      0 20.20.0.11:1234         20.20.230.114:54176     ESTABLISHED

tcp        0      0 20.20.0.11:1234         20.20.254.190:58749     ESTABLISHED

To check which all ports are listening on server:

root@client-ubuntu:/etc# sudo lsof -i -n -P | grep LISTEN

systemd-r   643 systemd-resolve   13u  IPv4   17611      0t0  TCP 127.0.0.53:53 (LISTEN)

vsftpd      759            root    3u  IPv6   21071      0t0  TCP *:21 (LISTEN)

sshd        7a4            root    3u  IPv4 a362254      0t0  TCP *:22 (LISTEN)

sshd        7a4            root    4u  IPv6 a362256      0t0  TCP *:22 (LISTEN)

apache2     a55            root    4u  IPv6   22102      0t0  TCP *:a0 (LISTEN)

apache2     a55            root    6u  IPv6   22106      0t0  TCP *:443 (LISTEN)

cupsd     16539            root    6u  IPv6 95162a4      0t0  TCP [::1]:631 (LISTEN)

cupsd     16539            root    7u  IPv4 95162a5      0t0  TCP 127.0.0.1:631 (LISTEN)

apache2   16559        www-data    4u  IPv6   22102      0t0  TCP *:a0 (LISTEN)

apache2   16559        www-data    6u  IPv6   22106      0t0  TCP *:443 (LISTEN)

apache2   16560        www-data    4u  IPv6   22102      0t0  TCP *:a0 (LISTEN)

apache2   16560        www-data    6u  IPv6   22106      0t0  TCP *:443 (LISTEN)

root@client-ubuntu:/etc# 


root@ubuntu-1804:~# netstat

Active Internet connections (w/o servers)

Proto Recv-Q Send-Q Local Address           Foreign Address         State      

tcp        0      0 ubuntu-1804:ssh         systest-runner:38842    ESTABLISHED

Active UNIX domain sockets (w/o servers)

Proto RefCnt Flags       Type       State         I-Node   Path

unix  2      [ ]         DGRAM                    1958810  /run/user/0/systemd/notify

unix  3      [ ]         DGRAM                    13499    /run/systemd/notify

unix  7      [ ]         DGRAM                    13520    /run/systemd/journal/socket

unix  10     [ ]         DGRAM                    13525    /run/systemd/journal/dev-log

unix  2      [ ]         DGRAM                    13530    /run/systemd/journal/syslog

unix  3      [ ]         STREAM     CONNECTED     18667    

unix  3      [ ]         DGRAM                    12871    


List All TCP Ports

List all TCP ports by running:

root@ubuntu-1804:~# netstat -at

Active Internet connections (servers and established)

Proto Recv-Q Send-Q Local Address           Foreign Address         State      

tcp        0      0 0.0.0.0:5678            0.0.0.0:*               LISTEN     

tcp        0      0 0.0.0.0:ftp             0.0.0.0:*               LISTEN     

tcp        0      0 localhost:domain        0.0.0.0:*               LISTEN     

tcp        0      0 0.0.0.0:ssh             0.0.0.0:*               LISTEN     

tcp        0      0 ubuntu-1804:ssh         systest-runner:38842    ESTABLISHED

tcp6       0      0 [::]:12865              [::]:*                  LISTEN     

root@ubuntu-1804:~# 


List All UDP Ports

root@ubuntu-1804:~# netstat -au

Active Internet connections (servers and established)

Proto Recv-Q Send-Q Local Address           Foreign Address         State      

udp        0      0 localhost:domain        0.0.0.0:*                          

udp        0      0 0.0.0.0:bootpc          0.0.0.0:*                          

udp        0      0 ubuntu-1804:ntp         0.0.0.0:*                          

udp        0      0 ubuntu-1804:ntp         0.0.0.0:*                          

udp        0      0 localhost:ntp           0.0.0.0:*                          

udp        0      0 0.0.0.0:ntp             0.0.0.0:*                          

udp6       0      0 ubuntu-1804:ntp         [::]:*                             

udp6       0      0 ubuntu-1804:ntp         [::]:*                             

udp6       0      0 ubuntu-1804:ntp         [::]:*                             

udp6       0      0 localhost:ntp           [::]:*                             

udp6       0      0 [::]:ntp                [::]:*                             

root@ubuntu-1804:~# 


List Only Listening Ports

To return a list of only listening ports for all protocols, use:

Active UNIX domain sockets (only servers)

Proto RefCnt Flags       Type       State         I-Node   Path

unix  2      [ ACC ]     STREAM     LISTENING     13540    /run/systemd/fsck.progress

unix  2      [ ACC ]     SEQPACKET  LISTENING     13536    /run/udev/control

unix  2      [ ACC ]     STREAM     LISTENING     1958813  /run/user/0/systemd/private

unix  2      [ ACC ]     STREAM     LISTENING     1958817  /run/user/0/gnupg/S.gpg-agent.browser

unix  2      [ ACC ]     STREAM     LISTENING     1958818  /run/user/0/gnupg/S.gpg-agent

unix  2      [ ACC ]     STREAM     LISTENING     1958819  /run/user/0/gnupg/S.gpg-agent.ssh

unix  2      [ ACC ]     STREAM     LISTENING     1958820  /run/user/0/gnupg/S.dirmngr

unix  2      [ ACC ]     STREAM     LISTENING     1958821  /run/user/0/gnupg/S.gpg-agent.extra

unix  2      [ ACC ]     STREAM     LISTENING     15986    @irqbalance579.sock

unix  2      [ ACC ]     STREAM     LISTENING     15153    /var/run/vmware/guestServicePipe

unix  2      [ ACC ]     STREAM     LISTENING     15201    /run/uuidd/request

unix  2      [ ACC ]     STREAM     LISTENING     15207    /var/run/dbus/system_bus_socket

unix  2      [ ACC ]     STREAM     LISTENING     15214    /run/acpid.socket

unix  2      [ ACC ]     STREAM     LISTENING     19865    /var/run/.vmw_conn_notify_socket

unix  2      [ ACC ]     STREAM     LISTENING     13502    /run/systemd/private

unix  2      [ ACC ]     STREAM     LISTENING     13518    /run/systemd/journal/stdout

root@ubuntu-1804:~# 


To enable nfs on server:

Systemctl enable --now ngs-server

Rpm -q nfs-utils

Mkdir -p /srv/nfs/storage

Who all can access

/srv/nfs/storage 192.168.100.0/24(rw sync insecure)


To install cronos

Python3 setup.py install

Since it is running as daemen ..we need to configure it

root@systest-runner:~[33656]# cd /etc/cr

cracklib/     cron.d/       cron.daily/   cron.hourly/  cron.monthly/ cron.weekly/  

• crontab -e To edit current user’s crontab file

• crontab -l To display contents of the crontab file

• crontab -u [username] To edit any other user’s crontab file

• crontab -r To remove the crontab file of the current user’s

crontab -i To display a prompt before removing the current user’s crontab file


Git commands every automation QA engineer should know


git init -b <branch_name> Initializes a new Git repository and creates a new branch with the specified name.
git add -p Allows you to select which changes to add to the staging area.
git commit -m "Commit message"  Allows you to specify a custom commit message.
git status -v  Provides more detailed information about the status of the repository.
git branch -a Lists all branches in the repository, including remote branches.
git checkout -b <new_branch_name>  Creates a new branch and switches to it.
git merge <branch_name>  Merges the specified branch into the current branch.
git push origin <branch_name>  Pushes the current branch to the remote repository called "origin".
git fetch origin  Fetches changes from the remote repository called "origin".
git reset --hard <commit_hash>  Resets the working directory to the specified commit.
git checkout .  Undoes changes to all files in the working directory.
git log --oneline  Displays the history of commits in a single line format.
git stash Saves the current state of the working directory to the stash.
git stash pop  Restores the current state of the working directory from the stash.
git branch -d <local_branch_name>  allows you to delete a local branch only if you’re currently not in and viewing or having unpushed commits or unmerged changes.
git branch -D <local_branch_name>  Here -D is an alias for - - delete - - force It deletes a local branch fircefully even after having unmerged changes (use this with caution⛔️)
git push origin -d <remote_branch_name>  allows you to delete a remote branch in remote repo named origin


Additional tips

Use a consistent naming convention for your branches. This will make it easier to track your changes and identify which branch is associated with a particular feature or bug fix.

Use descriptive commit messages. This will help you and others understand what changes were made in each commit.

Use a pull request workflow. This will allow you to get feedback on your changes before merging them into the main branch.

Use a continuous integration server. This will help you to automatically test your code after each commit.


mPycharm tips 

In MAC Alt is Option 

to find some script: Ctrl + Shift + F 

Cmd B ## to see the class or function in use 

Cmd Shift + to expand complete file Cmd Shift - to collapse complete file 

Cmd + to expand code

Cmd - to collapse block of code 

For comment and un-comment Cmd / 

Auto complete/help Ctrl Space 

Full select

Option + Cmd + T 

To select line continuously Shift + Option ->

Option + Enter to fix typo error 

to fix error: alt + enter

Command shift + == to exapnd all for particular def : shift - or + 

Command shift - == to collaspe all ctrl + space for help

double shift to find script in pycharm 


Programs:

=========

Python3 program to Find missing # integers in list 

>>> def find_missing(lst):

...     return sorted(set(range(lst[0],lst[-1]) - set(lst)))

... 

>>> lst = [1, 2, 4, 6, 7, 9, 10]

>>> lst

[1, 2, 4, 6, 7, 9, 10]

>>> 


## Validate IP

>>> def validate_ip(IP):

...     import re

...     res = re.match("([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$", IP)

...     if res == None:

...             return "Invalid IP address"

...     else:

...             oct1 = res.group(1)

...             oct2 = res.group(2)

...             oct3 = res.group(3)

...             oct4 = res.group(4)

...             if int(oct1) > 255 or int(oct2) > 255 or int(oct3) > 255 or int(oct4) > 255:

...                     print("Input {} is wrong".format(IP))

...             else:

...                     print("Input {} is correct".format(IP))

... 

>>> IP = "192.168.0.280"

>>> validate_ip(IP)

Input 192.168.0.280 is wrong

>>> 

>>> IP = "192.168.0.280.."

>>> validate_ip(IP)

'Invalid IP address'

>>> 

>>> IP = "0.0.0.0"

>>> validate_ip(IP)

Input 0.0.0.0 is correct

>>> 

>>> IP = "255.255.255.255"

>>> validate_ip(IP)

Input 255.255.255.255 is correct

>>> 


If you have a dictionary like this -> d1={“k1′′:10,”k2′′:20,”k3”:30}. How would you increment values of all the keys ? 

>>> d1={"k1":10,"k2":20,"k3":30}

>>> d1.keys()

dict_keys(['k1', 'k2', 'k3'])

>>> 

>>> for i in d1.keys():

...     d1[i] += 1

... 

>>> d1

{'k1': 11, 'k2': 21, 'k3': 31}

>>> 


## How to create dictionary from two lists 

>>> keys = ["a", "b", "c"]

>>> values = [1,2,3]

>>> res = {keys[i]: values[i] for i in range(len(keys))}

>>> res

{'a': 1, 'b': 2, 'c': 3}

>>> 

>>> 

>>> dict(zip(keys,values))

{'a': 1, 'b': 2, 'c': 3}

>>> 


Write a one-liner that will count the number of capital letters in a file. Your code should work even if the file is too big to fit in memory. 

nlekhak@nlekhak-a01 Downloads % python3

Python 3.8.9 (default, Mar 30 2022, 13:51:17) 

[Clang 13.1.6 (clang-1316.0.21.2.3)] on darwin

Type "help", "copyright", "credits" or "license" for more information.

>>> with open("/Users/nlekhak/Downloads/debug.txt", "r") as f:

...     count = 0

...     text = f.read()

...     for char in text:

...             if char.isupper():

...                     count += 1

...     print(count)

... 

128

>>> 


How can you find the minimum and maximum values present in a tuple? 

• >>>  tup1 = (1,2,3,4,5) >>> 

• >>>  min(tup1) 1 

>>> 

• >>>  tup2 = (1,2,3,4,5) 

• >>>  max(tup2) 5

>>>

>>> 


If you have a list like this -> [1,”a”,2,”b”,3,”c”]. How can you access the 2nd, 4th and 5th elements from this list? 

>>> lst = [1,"a",2,"b",3,"c"]

>>> lst

[1, 'a', 2, 'b', 3, 'c']

>>> 

>>> indices = [1,3,4]

>>> 

>>> for i in indices:

...     print(lst[i])

... 

a

b

3

>>> 


Write a python program to print the following pattern -> 

>>> for i in range(1,6):

...     print(str(i)*i)

... 

1

22

333

4444

55555


Pyramid pattern of numbers 

>>> rows = 5

>>> for i in range(1, rows+1):

...     for j in range(1, i+1):

...             print(j, end="")

...     print("")

... 

1

12

123

1234

12345

>>> 


How do we convert the string to lowercase? str = 'XYZ'

print(str.lower()) 


Write Python code to sort a numerical dataset? 

The code to sort a numerical dataset is as follows: 

list = [ "13", "16", "1", "5" , "8"] list = [int(x) for x in list] list.sort()

print(list) 

## on list sort will only work on integers ## set don’t have sort attribute 


Create a single string from all the elements in the list 

x = ["Mindmajix", "Online", "Training"] print(" ".join(x)) 


Check the memory usage of an object 

import sys

x = 10 print(sys.getsizeof(x)) 


Find the most frequent value in a list 

test = [1, 2, 3, 9, 2, 7, 3, 5, 9, 9, 9] print(max(set(test), key = test.count)) 


You are working on a Python script that compares data within sets. Given the following sets, what code can you provide to determine if A is a superset of B?

A = {1, 2, 3, 4, 5} 

B = {1, 2, 3} C = {1, 2, 3} 

print(A.issuperset(B)) 


What is the Python syntax for defining an empty set literal? 

set() 


## Remove 

animals = ['cat', 'dog', 'chicken', 'rooster', 'cat', 'cow', 'horse', 'cat', 'bird', 

'cat']

>>> animals.remove('cat')

>>>

>>> animals

['dog', 'chicken', 'rooster', 'cat', 'cow', 'horse', 'cat', 'bird', 'cat'] 

## removes the first match element found 



Which data structure can you use as keys for your dictionary? tuple 

What syntax in functions would you use to pass a varied number of non- keyword arguments?

*args 


## byte object are machine readable strings on python ##normal string what we used it human readable string 

Remember:

● str(variable)convertsvariabletoastring. 

● byte(variable)convertsvariabletoabytesobject. 


Also:

● variable.decode()convertsvariabletoastring. 

● variable.encode()convertsvariabletoabytesobject. 


# Implement your function below. non repeating char in string

>>> def non_repeat(str):
...     cnt = {}
...     for c in str:
...             if c in cnt:
...                     cnt[c] += 1
...             else:
...                     cnt[c] = 1
...     for c in str:
...             if cnt[c] == 1:
...                     return c
...     return None
... 
>>> 
>>> non_repeating("abcab")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'non_repeating' is not defined
>>> non_repeat("abcab")
'c'
>>> non_repeat("abab")
>>> 
>>> non_repeat("aabbbc")
'c'
>>> 
>>> non_repeat("aabbdbc")
'd'
>>> 


Find common elements between lists. 

• >>>  list_a1 = [1, 3, 4, 6, 7, 9] 

• >>>  list_a2 = [1, 2, 4, 5, 9, 10] >>> 

• >>>  set(list_a1).intersection(set(list_a2))

•  {1, 4, 9}

>>> 


## Most frequent element 

• >>>  list1 = [1, 3, 1, 3, 2, 1] >>> 

• >>>  print(max(set(list1), key = list1.count))

•  1


Question: How a file is deleted in Python?

Answer: The file can be deleted by either of these commands: 

os.remove(filename)

os.unlink(filename) 


Question: What are Python modules?

Answer: A file containing Python code like functions and variables is a Python module. A Python module is an executable file with a .py extension.

Python has built-in modules some of which are:

● os

● sys

● math

● random

● datatime 

● JSON


Screen:

To create new screen: screen -S nlekhak

To reconnect same screen -rd nlekhak

To check all created screen: screen -ls

To login to others screen: screen -xs nlekhak


root@systest-runner:~[63085]# screen -ls

There are screens on:

        29356.lekhak1   (11/28/2022 11:42:03 PM)        (Detached)


root@systest-runner:~[63076]# screen -X -S 29356 quit

root@systest-runner:~[63077]# 


To check which screen you are in: 

# echo $STY

19401.lekhak1






No comments:

Post a Comment