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

yipeiwu_com6年前Python基础

本文实例讲述了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 time
import socket
import threading
import traceback
import subprocess
def 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
      break
if __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 time
import socket
def 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()
      break
if __name__ == "__main__":
  server_list = []
  connPort = 47091
  readtarget()
  if server_list != []:
    for host in server_list:
      connserver(host, connPort)

servers.txt

# server ip list
192.168.0.139

三. 运行效果

python serverCmd.py

[+] Server is running on port:47091 at 20161013 17:50:19
[+] Connect success -> ('192.168.0.241', 4255) at 20161013 17:50:32
[+] Receive:hello
[+] Receive:你好
[+] Receive:cmd ip
'ip' 不是内部或外部命令,也不是可运行的程序
或批处理文件。

[+] Receive:cmd ipconfig

Windows IP 配置

以太网适配器 本地连接:

   连接特定的 DNS 后缀 . . . . . . . :
   本地链接 IPv6 地址. . . . . . . . : ****::****:****:****:*******
   IPv4 地址 . . . . . . . . . . . . : 192.168.0.139
   子网掩码  . . . . . . . . . . . . : 255.255.255.0
   默认网关. . . . . . . . . . . . . : 192.168.0.1

隧道适配器 isatap.{****-6122-4F83-8828-****}:

   媒体状态  . . . . . . . . . . . . : 媒体已断开
   连接特定的 DNS 后缀 . . . . . . . :

[+] Receive:cmd ping www.baidu.com

正在 Ping www.a.shifen.com [180.97.33.108] 具有 32 字节的数据:
来自 180.97.33.108 的回复: 字节=32 时间=66ms TTL=36
来自 180.97.33.108 的回复: 字节=32 时间=66ms TTL=36
来自 180.97.33.108 的回复: 字节=32 时间=64ms TTL=36
来自 180.97.33.108 的回复: 字节=32 时间=65ms TTL=36

180.97.33.108 的 Ping 统计信息:
    数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
往返行程的估计时间(以毫秒为单位):
    最短 = 64ms,最长 = 66ms,平均 = 65ms

[+] Receive:要结束了
[+] Receive:close session
[+] Quit success

python clientCmd.py

[*] Please input command:
hello
[+] Send 192.168.0.139:47091 -> hello
[+] Receive :[Server]success

[*] Please input command:
你好
[+] Send 192.168.0.139:47091 -> 你好
[+] Receive :[Server]success

[*] Please input command:
cmd ip
[+] Send 192.168.0.139:47091 -> cmd ip
[+] Receive :[Server]success

[*] Please input command:
cmd ipconfig
[+] Send 192.168.0.139:47091 -> cmd ipconfig
[+] Receive :[Server]success

[*] Please input command:
cmd ping www.baidu.com
[+] Send 192.168.0.139:47091 -> cmd ping www.baidu.com
[+] Receive :[Server]success

[*] Please input command:
要结束了
[+] Send 192.168.0.139:47091 -> 要结束了
[+] Receive :[Server]success

[*] Please input command:
close session
[+] Send 192.168.0.139:47091 -> close session
[+] Receive :[Server]success

更多关于Python相关内容可查看本站专题:《Python Socket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

python字典的setdefault的巧妙用法

现在有一个员工字典,类似这样的结构 staff_dic = {"name":"灭霸", "age": 10000, "hobbies":["打响指", "扣脚"]} 假设我们要给员...

pyqt弹出新对话框,以及关闭对话框获取数据的实例

如下所示: from PyQt4 import QtGui,QtCore import sys class Web_Browser(QtGui.QDialog): def __i...

简析Python的闭包和装饰器

简析Python的闭包和装饰器

什么是装饰器? 装饰器(Decorator)相对简单,咱们先介绍它:“装饰器的功能是将被装饰的函数当作参数传递给与装饰器对应的函数(名称相同的函数),并返回包装后的被装饰的函数”,听起来...

centos6.8安装python3.7无法import _ssl的解决方法

公司运维提供的服务器是centos6.8,打算在上面装python3.7,结果费尽周折,按照网上的步骤python3.7能成功安装,但是import ssl却报找不到_ssl模块的错误:...

pytorch构建多模型实例

pytorch构建双模型 第一部分:构建"se_resnet152","DPN92()"双模型 import numpy as np from functools import pa...