python远程执⾏命令1. 使⽤os模块远程执⾏命令
服务端代码
1import socket
2import os
3
4 sh_server = socket.socket()  #创建⼀个socket对象
5 sh_server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)  #重置IP和端⼝
6 sh_server.bind(('127.0.0.1',8001))  #绑定服务器IP和端⼝
7 sh_server.listen(5)  #设置最⼤监听数
8
9while True: #链接循环
10    conn,addr = sh_server.accept()  #阻塞,等待客户端过来链接
11
12while True: #通信循环
13# 接收客户端发送过来的消息
14    cmd = v(buffer_size).decode('utf-8')
15#使⽤os模块中的popen远程执⾏命令
16    data = os.popen(cmd)
17    res_ad()
18#执⾏结果发送给客户端
19    conn.send(de('gbk'))
20print(res_msg)
21print(len(res_msg))
22 conn.close()
23
客户端代码
1import socket
2
3 sh_client = socket.socket() #创建socket对象
4 sh_client.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
5
6 t(('127.0.0.1',8001))  #链接服务端
7
8while True: #通信循环
9    cmd = input("请输⼊要执⾏的命令:")
10if cmd == '': continue
11if cmd =='exit'or cmd =='quit':break
12    sh_client.de('utf-8'))
13    res_info = v(1024).decode('gbk')
14print('命令执⾏结果是:',res_info)
15 sh_client.close()
2. 使⽤subprocess模块执⾏远程命令
服务端代码
1import socket
2import subprocess
3
4 sh_server = socket.socket()
5 sh_server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)  #重置IP和端⼝
6 sh_server.bind(('127.0.0.1',8001))
7 sh_server.listen(5)
8
9while True: #链接循环
10    conn,addr = sh_server.accept()  #阻塞,等待客户端过来链接
11print('客户端信息',conn,addr)
12
13while True: #通信循环
14# 接收客户端发送过来的消息
15print('----------接收命令')
16        cmd = v(buffer_size).decode('utf-8')
17print('要执⾏的命令是:',cmd)
18if cmd == 'exit'or cmd == 'quit':break
19#使⽤subprocess模块执⾏远程命令
20        ret = subprocess.Popen(cmd,shell=True,
21                                stdout = subprocess.PIPE,
22                                stderr = subprocess.PIPE,
23                                stdin = subprocess.PIPE)
24
25        err = ad()
26if err:
27            ret_msg = err
28else:
29            ret_msg = ad()
30if not ret_msg:
31            ret_msg = "命令执⾏成功".encode('gbk')input命令
32print('---------命令执⾏完成')
33        conn.send(ret_msg)
34
35    conn.close()
客户端代码
1import socket
2
3 sh_client = socket.socket()
4 sh_client.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) 5
6 t(('127.0.0.1',8001))
7
8while True: #通信循环
9    cmd = input("请输⼊要执⾏的命令:")
10if cmd == '': continue
11if cmd =='exit'or cmd =='quit':break
12    sh_client.de('utf-8'))
13    res_info = v(1024).decode('gbk')
14print('命令执⾏结果是:',res_info)
15 sh_client.close()

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。