Python socket c/s远程命令执行案例

一. 前言

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

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

发送:cmd [command]形式消息,让远程主机执行命令(本地主机无回显)
发送:close session消息,双方关闭会话。


二. 源码

可以到Linux公社资源站下载:

——————————————分割线——————————————

免费下载地址在 http://linux.linuxidc.com/

用户名与密码都是www.linuxidc.com

具体下载目录在 /2017年资料/3月/14日/Python socket cs远程命令执行案例/

下载方法见 http://www.linuxidc.com/Linux/2013-07/87684.htm

——————————————分割线——————————————

:
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