标签:sock pip exe nes ip) als false policy lis
1.获取百度返回信息import socket host = "www.baidu.com" port = 80 ip = socket.gethostname(host) #获取访问百度的时候解析出来的IP地址。(vip) print ("connect server ip = {0}".format(ip)) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((ip, port)) #s.sendall(" ") #python2在sendall()中必须是字符串(str)形式 ,此处不用这种形式。 s.sendall("GET / HTTP/1.1 \r\nHost:www.baidu.com\r\n\r\n".encode("utf-8")) #python3在sendall()中必须是字节(beat)形式 ##在制定的http层次的协议上,百度有自己的规定,如果发过去的字符串不符合规定,百度是不会返回信息的,要符合对方的规则。 data = s.recv(2048) #接收数据 print (data)
2.socket实现ssh连接终端
客户端:
import socket import time if __name__ == "__main__": host = "192.168.0.103" port = 12345 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) stat = 1 while 1: cmd = raw_input("{0} >>> ".format(host)) if cmd.lower() == "exit": exit() if not cmd: continue s.sendall(cmd) data = s.recv(2048) if len(data) > 0: stat = 1 print ("{0}".format(data)) else: stat += 1 time.sleep(1) if stat == 5: break
服务端:
import socket import commands import time host = "192.168.0.103" port = 12345 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print ("server host = {0} port = {1}".format(host, port)) s.bind((host, port)) s.listen(6) conn, addrclient = s.accept() print ("connect from {0}".format(addrclient)) stat = 1 while 1: cmd = conn.recv(2048) if len(cmd) > 0: stat = 1 status, output = commands.getstatusoutput(cmd) conn.sendall(output) else: stat += 1 time.sleep(1) if stat == 5: break
这个脚本还欠缺很多功能,也存在不少bug,还待后期去完善和修复,待续ing...
3.专门用来SSH的模块
在python模块里面专门用来ssh连接的模块:paramiko
用网页就可以连接上服务端,基于ssh协议,不需要写服务端
是一个ssh版的客户端
安装paramiko
# pip install paramiko
创建连接脚本:
vim para.py #注意名字不能用paramiko.py,不然脚本执行过程中会有问题。
import time import paramiko client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #用来设置know-host client.connect(hostname="192.168.0.103", port=22, username="root", password="1q2w3e") stat = 1 while 1: cmd = raw_input("{0}>> ".format('192.168.0.103')) if cmd: stat = 1 stdin, stdout, stderr = client.exec_command(cmd) for std in stdout.readlines(): print (std) else: stat += 1 time.sleep(1) if stat == 5: break
执行即可连接服务器。
标签:sock pip exe nes ip) als false policy lis
原文地址:http://blog.51cto.com/286577399/2057229