首页 > 代码库 > 通过python socket远程执行命令,并返回值
通过python socket远程执行命令,并返回值
#!/usr/bin/env python
# TCP-Server
import socket
import subprocess
sk_obj = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sk_obj.bind((‘127.0.0.1‘,8000))
sk_obj.listen(5)
while True:
conn,ipaddr = sk_obj.accept()
print (‘connection from ip: %s‘ % ipaddr[0])
while True:
try:
from_recv = conn.recv(8096)
if len(from_recv) == 0:continue
print (‘from ip : %s information : %s‘ % (ipaddr[0],from_recv))
res = subprocess.Popen(from_recv.decode(‘utf-8‘),shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
msg = res.stdout.read()
if len(msg) == 0:
msg = res.stderr.read()
conn.send(msg)
except Exception:
break
conn.close()
sk_obj.close()
#!/usr/bin/env python
# TCP-Client
import socket
import sys
sk_obj=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sk_obj.connect((‘127.0.0.1‘,8000))
while True:
msg = raw_input(‘-->‘).strip()
if len(msg)==0:continue
sk_obj.send(msg.encode(‘utf-8‘))
data = http://www.mamicode.com/sk_obj.recv(8096)
print (‘Server send information : %s‘ % data.decode(‘utf-8‘))
sk_obj.close()
本文出自 “gswcfl” 博客,请务必保留此出处http://guoshiwei.blog.51cto.com/2802413/1924265
通过python socket远程执行命令,并返回值