700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Python连接telnet客户端连接服务端程序

Python连接telnet客户端连接服务端程序

时间:2021-05-02 11:23:54

相关推荐

Python连接telnet客户端连接服务端程序

import loggingimport telnetlibimport timeclass TelnetClient():def __init__(self,):self.tn = telnetlib.Telnet()# 此函数实现telnet登录主机def login_host(self,host_ip,username,password):try:# self.tn = telnetlib.Telnet(host_ip,port=23)self.tn.open(host_ip,port=23)except:logging.warning('%s网络连接失败'%host_ip)return False# 等待login出现后输入用户名,最多等待10秒self.tn.read_until(b'login: ',timeout=10)self.tn.write(username.encode('ascii') + b'\n')# 等待Password出现后输入用户名,最多等待10秒self.tn.read_until(b'Password: ',timeout=10)self.tn.write(password.encode('ascii') + b'\n')# 延时两秒再收取返回结果,给服务端足够响应时间time.sleep(2)# 获取登录结果# read_very_eager()获取到的是的是上次获取之后本次获取之前的所有输出command_result = self.tn.read_very_eager().decode('ascii')if 'Login incorrect' not in command_result:logging.warning('%s登录成功'%host_ip)return Trueelse:logging.warning('%s登录失败,用户名或密码错误'%host_ip)return False# 此函数实现执行传过来的命令,并输出其执行结果def execute_some_command(self,command):# 执行命令self.tn.write(command.encode('ascii')+b'\n')time.sleep(2)# 获取命令结果command_result = self.tn.read_very_eager().decode('ascii')logging.warning('命令执行结果:\n%s' % command_result)# 退出telnetdef logout_host(self):self.tn.write(b"exit\n")def StartCheckWeak(): host_ip = '192.168.32.171' username = 'root' password = 'abcd1234' command = 'whoami' telnet_client = TelnetClient() # 如果登录结果返加True,则执行命令,然后退出 if telnet_client.login_host(host_ip,username,password): telnet_client.execute_some_command(command) telnet_client.execute_some_command("cd /bin && ls") telnet_client.execute_some_command("uname -a") telnet_client.logout_host() if __name__ == '__main__':threads = [] for i in range(0, 10): t = threading.Thread(target=StartCheckWeak) t.setDaemon(True) threads.append(t) t.start() for i in range(0, len(threads)): threads[i].join() """ host_ip = '192.168.32.171' username = 'root' password = 'abcd1234' command = 'whoami' telnet_client = TelnetClient() # 如果登录结果返加True,则执行命令,然后退出 if telnet_client.login_host(host_ip,username,password): telnet_client.execute_some_command(command) telnet_client.execute_some_command("cd /bin && ls") telnet_client.execute_some_command("uname -a") telnet_client.logout_host() """ """if __name__ == '__main__':host_ip = '192.168.220.129'username = 'root'password = 'abcd1234'command = 'whoami'telnet_client = TelnetClient()# 如果登录结果返加True,则执行命令,然后退出if telnet_client.login_host(host_ip,username,password):telnet_client.execute_some_command(command)telnet_client.logout_host()"""

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。