编写一个程序,实现客户端能在服务端远程执行命令,并把命令结果在客户端打印出来
服务端:192.168.5.131
客户端:192.168.5.134
[[email protected] ~]# cat client.py #!/usr/bin/env python #-*- coding:utf-8 -*- import sys import tab # tab模块用于让客户端支持命令tab补齐,需要自己编写该模块,参考:tab.py import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((‘192.168.5.131‘, 1234)) while True: cmd = raw_input(‘Please input command: ‘).strip() if cmd == ‘exit‘ or cmd == ‘quit‘: sys.exit() if cmd: s.sendall(cmd) data = s.recv(1024) print data s.close()
[[email protected] ~]# cat server.py #!/usr/bin/env python #-*- coding: utf8 -*- import socket from subprocess import Popen, PIPE s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((‘192.168.5.131‘, 1234)) s.listen(5) connect, address = s.accept() while True: cmd = connect.recv(1024) p = Popen(cmd, stdout=PIPE, stderr=PIPE) stdout = p.stdout.read() stderr = p.stderr.read() if stdout: connect.sendall(stdout) elif stderr: connect.sendall(stderr) s.close()
先运行 server.py ,然后在客户端执行远程命令:
[[email protected] ~]# python client.py Please input command: ls anaconda-ks.cfg client.py install.log install.log.syslog server.py Please input command: df Filesystem 1K-blocks Used Available Use% Mounted on /dev/sda3 20338948 1352204 17953580 8% / tmpfs 767420 0 767420 0% /dev/shm /dev/sda1 99150 27809 66221 30% /boot Please input command: exit
原文地址:https://www.cnblogs.com/pzk7788/p/8148698.html
时间: 2024-11-09 22:19:18