first round : typical question of network ,TCP, python
upper()
tcp three-way handshake
how to show routing table in linux
second round : networking question
BGP
path attribute
loop protection in BGP :
RR : how RR work to eliminate loop protection
confederation
TCP/IP
congestion windows
difference between RSt and FIN
FIN :
A FIN is used to gracefully shutdown a TCP session.
A FIN packet is usually sent from server or client to terminate a connection, after establishment of TCP 3-way handshake and successful transfer of data.
A FIN is intended to terminate an established connection.
FIN says, "I finished talking to you, but I'll still listen to everything you have to say until you're done" (Wait for an ACK)
RST:
RST can be used to shutdown a session at any time.
A RST packet is sent either in the middle of the 3-way handshake when the server rejects the connection or is unavailable OR in the middle of data transfer when either the server or client becomes unavailble or rejects further communication without the formal 4-way TCP connection termination process.
A RST can be used that way as well, but can also be used to abort a connection that is only partially formed or is being rejected.
RST says, "There is no conversation. I am resetting the connection!"
How does TCP handle the duplicate segments and out of order segments?
By using sliding window protocol.
There are two computers A and B. Initial window size=4 packets. After every 4 packets B will send acknowledgment to A and will ask for 5th packet after 4 more packets same thing will happen so on. While sending 11th packet suppose that packet gets dropped then B will wait and won't give any acknowledgment to A. A will wait for some stipulated time then it'll retransmit packet 8-12 as B already have 8-10 it'll override those packets. Hence there'll be no duplication of packet (i.e Segment on Layer 4).
Suppose there's increase in drop rates say after every 3 packets. Then window size will reduce to 2. If dropping is continue then window size will become 1. So after every packet B will ACK. Then after some times drop rates are low. Drops are happening after every 20-30 packets then window size will increase.
This way TCP handles duplication and segmentation.
dupicate ACK and fast retransmit
Layer 2 troubleshooting
how many hosts for /31
since a point to point doesn't really need a broadcast address, instead of using a /30 which is 4 addresses, you can use a /31 and use 2 address and it works.
Using a /31 subnet mask helps conserve your IP address space for point to point links. It doubles the number of links that you can number from a given block of addresses.
cause of unicast flooding
The very cause of flooding is that destination MAC address of the packet is not in the L2 forwarding table of the switch. In this case the packet will be flooded out of all forwarding ports in its VLAN (except the port it was received on).
Let me explain the topology above:
- There are two multilayer switches, SW1 and SW2. Between these switches we have a trunk for VLAN 10 and 20.
- SW1 and SW2 have SVI interfaces with an IP address for VLAN 10 and 20.
- Host 1 and 4 are in VLAN 10.
- Host 2 and 3 are in VLAN 20.
- Host 1 uses 192.168.10.254 (SW1) as its default gateway.
- Host 2 uses 192.168.20.253 (SW2) as its default gateway.
This is a condition where the router still has a live ARP entry even though the switch's CAM table has flushed the corresponding entry. As a result, when the router receives a packet for a given host it is simply forwarded to the switch without first sending an ARP request (the IP : MAC mapping is still cached). The switch, however, no longer knows the port to which this MAC address is mapped (this entry having been aged out earlier). If the switch doesn't have a CAM entry for a given unicast MAC then it will flood packets for that MAC to all ports until it sees a response
As long as SW1 has an entry for host 2 in its MAC address table then there will be no problem since it will know how to reach its destination. Once there is no activity between host 1 and host 2(the arp table aging time is muc hlonger than the mac-address table aging time which is around 5min), SW1 will flush the MAC address of host 2 from its MAC address table and it won’t have a chance to learn it again until:
- The ARP entry for host 2 expires. This will trigger a new ARP request and SW1 will receive an ARP reply from host 2.
- Host 2 sends a broadcast message like an ARP request.
How do we fix this problem? There a number of solutions:
- Change the ARP table timeout so it matches the aging time of the MAC address table. When SW1 sends an ARP request for host 2, it will receive an ARP reply and will relearn its MAC address.
- Change your network design. Use a single router or multilayer switch as the default gateway for all VLANs.
A-----router-----C
\|
\| . b
A send unicast address to C , c cannot receive , will b receive the packges ?
third round : onscreen interview;45min
question 1:
there are serval switches , check whether the switches can be ssh into , and print the unreachable switch
# I use the pexpect to run the code
import paramiko
ip = []
def connct(ip):
ssh = paramiko.SSHClinet()
ssh.set_missing_host_key_policy(paramiko.AutoPolicy())
ssh.connect(ip,22,'root','123456')
if not ssh :
print ' the server %s can not be ping'%ip
ssh.close()
return 0
else : return 1
for ip in ip_list :
if connct(ip) == 0 :
ip.append(ip)
print ip
----------------------
stdin, stdout, stderr = ssh.exec_command(m)
outmsg,errmsg = stdout.read(),stderr.read() #读一次之后,stdout和stderr里就没有内容了,所以一定要用变量把它们带的信息给保存下来,否则read一次之后就没有了
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pexpect
def ssh_cmd(ip, passwd, cmd):
ret = -1
ssh = pexpect.spawn('ssh root@%s "%s"' % (ip, cmd))
ssh.logfile = sys.stdout
try:
i = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=5)
if i == 0 :
ssh.sendline(passwd)
elif i == 1:
ssh.sendline('yes\n')
ssh.expect('password: ')
ssh.sendline(passwd)
ssh.sendline(cmd)
r = ssh.read()
print r
ret = 0
except pexpect.EOF:
print "EOF"
ssh.close()
ret = -1
except pexpect.TIMEOUT:
print "TIMEOUT"
ssh.close()
ret = -2
return ret
利用pexpect模块我们可以做很多事情,由于他提供了自动交互功能,因此我们可以实现ftp,telnet,ssh,scp等的自动登录,还是比较实用的。根据上面的代码相信读者已经知道怎么实现了(python就是那么简单!)。
用上面的代码去完成任务还是比较费时间的,因为程序要等待自动交互出现,另外ubuntu用ssh连接就是比较慢,要进行一系列的验证,这样才体现出ssh的安全。我们要提高效率,在最短的时间内完成。后来我发现了python里面的paramiko模块,用这个实现ssh登录更加简单。看下面的代码:
#-*- coding: utf-8 -*-
#!/usr/bin/python
import paramiko
import threading
def ssh2(ip,username,passwd,cmd):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,22,username,passwd,timeout=5)
for m in cmd:
stdin, stdout, stderr = ssh.exec_command(m)
# stdin.write("Y") #简单交互,输入 ‘Y’
out = stdout.readlines()
#屏幕输出
for o in out:
print o,
print '%s\tOK\n'%(ip)
ssh.close()
except :
print '%s\tError\n'%(ip
if __name__=='__main__':
cmd = ['cal','echo hello!']#你要执行的命令列表
username = "" #用户名
passwd = "" #密码
threads = [] #多线程
print "Begin......"
for i in range(1,254):
ip = '192.168.1.'+str(i)
a=threading.Thread(target=ssh2,args=(ip,username,passwd,cmd))
a.start()
上面的程序还是有些技巧的:
1.利用多线程,同时发出登录请求,同时去连接电脑,这样速度快很多,我试了一下,如果不用多线程,直接一个一个挨着执行的话,大约5~10秒钟才能对一台电脑操作完,具体时间要根据命令的来决定,如果是软件安装或者卸载时间要更长一些。这样下来怎么也要一二十分钟,用多线程后就快多了,所有的命令执行完用了不到2分钟!
2.最好用root用户登录,因为安装或者卸载软件的时候如果用普通用户又会提示输入密码,这样又多了一次交互,处理起来就比较麻烦!安装软件时apt-get install xxx 最好加上“-y”参数,因为有时安装或删除软件时提示是否继续安装或卸载,这又是一次自动交互!加上那个参数后就没有人机交互了。
3. 循环时循环所有ip,因为计算机的ip是路由器自动分配的,保险起见,最好全部都执行,保证没有遗漏的主机
4.远端执行命令时如果有交互,可以这样用 stdin.write("Y")来完成交互,“Y”就是输入“Y”。
5.把所有的命令放到一个列表里面,遍历列表可以依次执行列表里面的命令
6.为了更好的进行控制,最好在电脑上提前把root用户打开,装好ssh服务器并让其开机自动执行
#检测服务器是否能ping通,在程序运行时,会在标准输出中显示命令的运行信息
def pingServer(server):
result=os.system('ping '+server+' -c 2')
if result:
print '服务器%s ping fail' % server
else:
print '服务器%s ping ok' % server
print result
import pexpect
def login_ssh_passwd(port="",user="",host="",passwd=""):
'''函数:用于实现pexepect实现ssh的自动化用户密码登录'''
# print 'ssh -p %s %s@%s' % (port,user, host)
if port and user and host and passwd:
ssh = pexpect.spawn('ssh -p %s %s@%s' % (port,user, host))
i = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=5)
if i == 0 :
ssh.sendline(passwd)
elif i == 1:
ssh.sendline('yes\n')
ssh.expect('password: ')
ssh.sendline(passwd)
index = ssh.expect (["#", pexpect.EOF, pexpect.TIMEOUT])
if index == 0:
print "logging in as root!"
ssh.interact()
elif index == 1:
print "logging process exit!"
elif index == 2:
print "logging timeout exit"
else:
print "Parameter error!"
def login_ssh_key(keyfile="",user="",host="",port=""):
'''函数:用于实现pexepect实现ssh的自动化密钥登录'''
if port and user and host and keyfile:
ssh = pexpect.spawn('ssh -i %s -p %s %s@%s' % (keyfile,port,user, host))
i = ssh.expect( [pexpect.TIMEOUT,'continue connecting (yes/no)?'], timeout=2)
# print '...................................',0
if i == 1:
ssh.sendline('yes\n')
index = ssh.expect (["#", pexpect.EOF, pexpect.TIMEOUT])
else:
index = ssh.expect (["#", pexpect.EOF, pexpect.TIMEOUT])
if index == 0:
print "logging in as root!"
ssh.interact()
elif index == 1:
print "logging process exit!"
elif index == 2:
print "logging timeout exit"
else:
print "Parameter error!"
def main():
'''主函数:实现两种方式分别的登录'''
# login_ssh_passwd(port='22',user='root',host='192.168.1.101',passwd='imooccs')
login_ssh_key(keyfile="/tmp/id_rsa",port='22',user='root',host='192.168.1.101')
if __name__ == "__main__":
main()
count the number of char in strings or files
import pprint
message = 'adnewihfsnfhoiwenfambdwuirhanfaeugh'
count = {}
------------------------
for kw in strings:
counts[kw] = counts.setdefault(kw, 0) + 1
-----------------------------
for char in message.upper():
count.setdefault(char,0)
count[char] += 1
print (count)
#pprint.pprint(count)
----------------------------------------------
counts = defaultdict(lambda: 0) # 使用lambda来定义简单的函数
for s in strings:
counts[s] += 1
question 2 :
there is a file with content as below :
'''switchname interface, input ,output
switch1,eth1,1234,3454
switch1,eth2,2335,3541
switch1,eth3,4567,2389'''
sort the output stream from high to low
list1 = []
with open('txt.py','r'0 as f :
for line in f.readlines():
if line.startswith('switch1'):
list1.append(line.strip())
list2 = sorted(list1,key=lambda x : x.split(',')[3],reverse =True)
(or)list1.sort(key=lambda a: a.split(',')[-1].strip(),reverse=True)
print(list1)
dict1 = {}
with open('txt.py','r') as f :
for lines in f.readlines():
if 'interface' in lines or len(lines) < 2:
continue
dict1[lines.split(',')[0] + lines.split(',')[1]] = lines.split(',')[3].strip()
print(dict1)
==>
{'switch1 eth1': '3454', 'switch1 eth2': '3541', 'switch1 eth3': "2389'''"}
print(sorted(dict1))
===> a list of key
['switch1 eth1', 'switch1 eth2', 'switch1 eth3']
print(dict1.sort())
===>
AttributeError: 'dict' object has no attribute 'sort'
print(sorted(dict1.items(),key = lambda x :x[1],reverse =True))
===>a list of items() tuple
[('switch1 eth2', '3541'), ('switch1 eth1', '3454'), ('switch1 eth3', "2389'''")]
#sort dictionary by values from high to low
#(wrong answer)for key, value in sorted(dict1.iteritems(), key=lambda (k,v): (v,k),reverse = True):
print "%s: %s" % (key, value)
from collections import OrderedDict
d_sorted_by_value = OrderedDict(sorted(dict1.items(), key=lambda x: x[1],reverse=True))
==>
OrderedDict([('switch1 eth2', '3541'), ('switch1 eth1', '3454'), ('switch1 eth3', "2389'''")])
for k, v in d_sorted_by_value.items():
print "%s: %s" % (k, v)
==>
switch1 eth2: 3541
switch1 eth1: 3454
switch1 eth3: 2389'''
print sorted([(value,key) for (key,value) in dict1.items()])
>>>list
[('2389', ' switch1eth3'), ('3454', 'switch1eth1'), ('3541', ' switch1eth2')]
from collections import OrderedDict
# regular unsorted dictionary
d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
# dictionary sorted by key
OrderedDict(sorted(d.items(), key=lambda t: t[0]))
===>
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
# dictionary sorted by value
OrderedDict(sorted(d.items(), key=lambda t: t[1]))
===>
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
sort dic by keys
for key in sorted(mydict.iterkeys()):
print "%s: %s" % (key, mydict[key])
forth round :
expalin uicast flooding
what is loop protection for ibgp , what should do with this ?
how RR works , how RR do the loop protection?
ibgp to external destinations , what should set ?
explain fast retransmission?
explain regular retransmission ?
receive window , what is receive windows for ? memeory congestion of the receiver
what is the maxium window size ? how to calculate the max window size ?
how to use linux to analyse the tcp restansmission? where is linux store the result ?(temporily file system)
netstat -s | grep -i retrans
h