首页 > 开发 > Python > 正文

Python socket套接字实现C/S模式远程命令执行功能案例

2024-09-09 19:02:47
字体:
来源:转载
供稿:网友

本文实例讲述了Python socket套接字实现C/S模式远程命令执行功能。分享给大家供大家参考,具体如下:

一. 前言

要求:

使用python的socket套接字编写服务器/客户机模式的远程命令执行脚本。

serverCmd.py 远程机器上用来执行客户端发送命令的脚本
clientCmd.py 本地机器上,向远程服务器发送命令的脚本
servers.txt  本地机器上,存放所有的远程服务器IP地址文件(仅支持第一个IP)

发送:cmd [command]形式消息,让远程主机执行命令(本地主机无回显)

发送:close session消息,双方关闭会话。

二. 源码

下载地址: 点击此处本站下载

注:

1. 代码注释较少,建议有一定套接字编程基础。
2. 或者直接简单部分修改IP使用。
3. clientCmd.py和servers.txt(修改IP地址后)放在同一目录。
4.程序为简单Demo,仅为学习记录。

serverCmd.py

#!/usr/bin/env python# coding:utf-8# Build by LandGrey#import timeimport socketimport threadingimport tracebackimport subprocessdef parsecmd(strings):  midsplit = str(strings).split(" ")  if len(midsplit) >= 2 and midsplit[0] == "cmd":    try:      command = subprocess.Popen(strings[4:], shell=True)      command.communicate()      print "/n"    except Exception, e:      print e.message      traceback.print_exc()def recvdata(port):  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  s.bind(('', port))  s.listen(1)  print "[+] Server is running on port:%s at %s" % (str(port), time.strftime("%Y%m%d %H:%M:%S", time.localtime()))  while True:    mainsocket, mainhost = s.accept()    print "[+] Connect success -> %s at %s" % (str(mainhost), time.strftime("%Y%m%d %H:%M:%S", time.localtime()))    if mainhost:      while True:        data = mainsocket.recv(1024)        if data:          print "[+] Receive:%s" % data          mainsocket.sendall("[Server]success")          parsecmd(data)        if data == "close session":          mainsocket.close()          print "[+] Quit success"          break      breakif __name__ == "__main__":  # some public variable  connPort = 47091  onethreads = threading.Thread(target=recvdata, args=(connPort,))  onethreads.start()

clientCmd.py

#!/usr/bin/env python# coding:utf-8# Build by LandGrey#import timeimport socketdef readtarget():  global server_list  with open(r"servers.txt") as f:    for line in f.readlines():      if line[0:1] != "#" and len(line.split(".")) == 4:        server_list.append(line)def connserver(host, port):  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  s.connect((host, port))  while True:    print "/n[*] Please input command:"    data = raw_input()    if not data:      break    s.sendall(data)    recvdata = s.recv(1024)    print "[+] Send %s:%s -> %s" % (host, str(connPort), data)    time.sleep(0)    if recvdata:      print "[+] Receive :%s" % recvdata    if data == "close session":      s.close()      breakif __name__ == "__main__":  server_list = []  connPort = 47091  readtarget()  if server_list != []:    for host in server_list:      connserver(host, connPort)
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表