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

 更新时间:2018年07月06日 09:59:23   作者:LandGrey  
这篇文章主要介绍了Python socket套接字实现C/S模式远程命令执行功能,涉及Python socket套接字编写服务器/客户机模式数据传输相关操作技巧,需要的朋友可以参考下

本文实例讲述了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程序设计有所帮助。

相关文章

  • Pyecharts中的饼图位置调整方式

    Pyecharts中的饼图位置调整方式

    这篇文章主要介绍了Pyecharts 饼图位置调整方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-11-11
  • Python实现数据透视表详解

    Python实现数据透视表详解

    今天小编就为大家分享一篇用Python实现数据的透视表的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-10-10
  • 详解pandas中MultiIndex和对象实际索引不一致问题

    详解pandas中MultiIndex和对象实际索引不一致问题

    这篇文章主要介绍了详解pandas中MultiIndex和对象实际索引不一致问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-07-07
  • python使用super()出现错误解决办法

    python使用super()出现错误解决办法

    这篇文章主要介绍了python使用super()出现错误解决办法的相关资料,对于TypeError: must be type, not classobj的错误进行处理,需要的朋友可以参考下
    2017-08-08
  • Python网络爬虫技术高阶用法

    Python网络爬虫技术高阶用法

    网络爬虫成为了自动化数据抓取的核心工具,Python 拥有强大的第三方库支持,在网络爬虫领域的应用尤为广泛,本文将深入探讨 Python 网络爬虫的高阶用法,包括处理反爬虫机制、动态网页抓取、分布式爬虫以及并发和异步爬虫等技术,帮助读者掌握高级Python爬虫技术
    2024-12-12
  • Flask项目中实现短信验证码和邮箱验证码功能

    Flask项目中实现短信验证码和邮箱验证码功能

    这篇文章主要介绍了Flask项目中实现短信验证码和邮箱验证码功能,需本文通过截图实例代码的形式给大家介绍的非常详细,需要的朋友可以参考下
    2019-12-12
  • pandas改变df列的顺序的方法实现

    pandas改变df列的顺序的方法实现

    本文主要介绍了pandas改变df列的顺序的方法实现,主要使用 Pandas 中的 reindex() 方法,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧
    2024-03-03
  • Python enumerate函数功能与用法示例

    Python enumerate函数功能与用法示例

    这篇文章主要介绍了Python enumerate函数功能与用法,结合实例形式分析了enumerate函数针对列表、字符串遍历操作相关使用技巧,需要的朋友可以参考下
    2019-03-03
  • Python项目打包成apk或者其他端的应用程序

    Python项目打包成apk或者其他端的应用程序

    本文主要介绍了使用Kivy和Buildozer将Python项目打包成Android APK文件的步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-11-11
  • python回归分析逻辑斯蒂模型之多分类任务详解

    python回归分析逻辑斯蒂模型之多分类任务详解

    这篇文章主要为大家介绍了python回归分析逻辑斯蒂模型之多分类任务详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-09-09

最新评论