远程命令执行Python

时间:2014-05-27 22:10:15

标签: python networking

出于教育目的,我设置了一个允许在Windows上执行远程命令的服务器 - 或者说,我尝试过。由于某种原因,命令行拒绝识别我发送的一些命令,但其他命令工作正常。例如,发送命令echo "Hello World!!!"会导致一个cmd窗口弹出读取“Hello World !!!”。精细。但是当我发送命令shutdown /s /t 30时,它给了我关闭命令的不正确的语法/帮助屏幕。当我发送命令msg * "Hello World"时,它告诉我'msg'不是可识别的内部或外部命令,可操作程序或批处理文件。这是我的服务器代码:

import socket
import sys

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_address = ('', 4242)
sock.bind(server_address)

sock.listen(1)

connection, client_address = sock.accept()
print("Connection established with %s " % str(client_address))
while True:
    command = input("Enter a command: ")
    connection.send(bytes(command, 'UTF-8'))
    confirm = connection.recv(128)
    if confirm == "yes":
        print("[+] Command executed successfully.")
    else:
        print("[-] Command failed to execute!!!")

这是我的客户代码:

import socket
import sys
import os

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_address = ('', 42042)
sock.bind(server_address)

sock.connect(('192.168.1.5', 4242))

while True:
    command = str(sock.recv(1024))
    try:
        os.system(command[2:]) # an odd thing, the commands somehow came out prefaced with "b'". Ideas?
        sock.send(bytes("yes", 'UTF-8'))
    except:
        sock.send(bytes("no", 'UTF-8'))

所以是的,就是这样。事实上只有一些命令搞砸了我真的很困惑。有人有什么想法吗?那么,“b”是什么?

1 个答案:

答案 0 :(得分:0)

str(sock.recv(1024))不是将字节对象转换为字符串的方法,您应该使用sock.recv(1024).decode('UTF-8')方法

您可以查看bytes.decode https://docs.python.org/3.4/library/stdtypes.html#bytes.decode

的文档

或此相关问题Best way to convert string to bytes in Python 3?