Python удаленное управление не работает

Привет, я написал инструмент для удаленного управления моим компьютером. Но это просто не работает. Я получаю соединение между сервером и клиентом, но если я посылаю команды, они не выполняются. Спасибо за помощь. Я проверил клиент и сервер по отдельности, и я думаю, что проблема на сервере (у него есть клиентский сокет - извиняюсь из-за этого извиняюсь) - он не выполняет пакетные команды

Сервер:

import socket, os, time
tester = 1

def main():
    conn = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    while True:
        time.sleep(1)
        try:
            conn.connect(("internalip",50001))
            income()
        except:
            main()



def income():
    while True:
        befehl = conn.recv(2048)
        print(befehl)
        if(befehl=="upload"):
            upload()

        elif(befehl=="download"):
            download()

        elif(befehl=="cmd"):
            cmdexe()

        else:
            conn.send("unknown command")


def cmdexe():    
    command = conn.recv(2048)
    print(command)
    if(command=="exit"):
        income()

    else:
        try:
            os.system(command)
        except:
            conn.send(str(exception)+" problem with cmd")
    income()


def upload():
    name=str(conn.recv(2048))
    if(name=="exit"):
        income()
    else:
        mode==str(conn.recv(1024))
        if(mode=="exit"):
            income()
        else:
            f = open(name,mode)
            try:
                f.write(str(conn.recv(8192)))
                f.close()
            except:
                conn.send("An Error with filehandling/upload")
                f.close()
                income()



def download():
    name=str(conn.recv(2048))
    if(name=="exit"):
        income()

    f= open(name,"r")
    try:
        conn.send(str(f.read()))
        income()
    except:
        f.close()
        conn.send("An Error with filehandling/upload")
        income()

#verbesserung: 1.automatisches setup 2.mehrere commands bei cmd

main()` 

Клиент:

import socket
from threading import Thread

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(("",50001))
s.listen(1)

conn,addr = s.accept()

def main():
    print(str(addr)+" is connected")
    print("Choose a command")
    #command_list={"upload", "download", "cmd"}
    #for i in range(3):
    #    print(str(command_list[i]))
    print("upload", "download", "cmd")

    befehl=raw_input(": ")

    if(befehl=="exit"):
        main()
    elif(befehl=="upload"):
        upload()
    elif(befehl=="download"):
        download()
    elif(befehl=="cmd"):
        cmd()
    else:
        print("Sorry, thats not a regular command")



def upload():
    conn.send("upload")

    name=raw_input("Geben sie den Namen ein, den die Datei haben soll!")
    if(name=="exit"):
        conn.send(name)
        main()
    conn.send(name)

    mode=raw_input("Send a for append or w to write: ")
    if(name=="exit"):
        main()
    elif(mode=="a"):
        conn.send("a")
    elif(mode=="w"):
        conn.send("w")
    else:
        print("Thats not a regulare mode")
        conn.send("exit")
    uf = open(raw_input("Choose the file you want to send: "),"r")
    conn.send("uf")
    main()

"""
def errorhandling():
    print(str(conn.recv(4096)))

Thread(target=errorhandling()).start()
"""
def download():
    conn.send("download")
    name=raw_input("Geben sie den Namen, der Datei ein, die sie downloaden moechten: ")
    if(name==exit):
        conn.send(name)
        main()
    conn.send(name)
    try:
        f=open(addr+"; "+name,"a")
        f.append(conn.recv(1048576))
    except:
        print("Error with filehandling: "+exception)
        main()

def cmd():
    conn.send("cmd")
    command = raw_input("Auszufuehrendes Kommando: ")
    if(command=="exit"):
        conn.send("exit")
        main()
    conn.send(command)
    cmd()


#verbesserung: Probleme mit mehreren Verbindungen 



main()

1 ответ

Любая причина, почему вы не используете существующий инструмент, такой как Fabric.

см.: http://www.fabfile.org/

Fabric - это библиотека Python (2.5-2.7) и инструмент командной строки для оптимизации использования SSH для развертывания приложений или задач системного администрирования.

Он предоставляет базовый набор операций для выполнения локальных или удаленных команд оболочки (обычно или с помощью sudo) и загрузки / выгрузки файлов, а также вспомогательные функции, такие как запрос работающего пользователя на ввод или прерывание выполнения.

Другие вопросы по тегам