python -- TCP "遠端控制"
python -- TCP "遠端控制" 指:先建立連線,再通過命令進行遠端控制伺服器。
在虛擬機器的程式碼程式
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import socket
import os
HOST = "192.168.1.185"
POST = 5000
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
addr = (HOST,POST)
s.bind(addr)
s.listen(1)
conn,addr = s.accept()
def getwinfile():
conn.send("我準備好接收了")
filename = conn.recv(1024)
fdata = conn.recv(20480)
with open(filename,"wb") as f:
f.write(fdata)
conn.send("finsh")
def putlinuxfile():
conn.send("我準備好傳輸了")
file = conn.recv(1024)
with open(file,"rb") as f:
fdata = f.read()
conn.send(fdata)
conn.send("finsh")
def main(addr):
print(addr)
while True:
data = conn.recv(1024)
print(data)
if data == "byebye":
break
if data == "wycf":
getwinfile()
continue
if data == "wysf":
putlinuxfile()
continue
f = os.popen(data)
ret = f.read()
if ret:
conn.send(ret)
else:
conn.send("finish")
conn.close()
s.close()
if __name__ =="__main__":
main(addr)
在真實機裡面的程式碼程式
import socket
HOST = "192.168.1.185"
PORT = 5000
addr = (HOST,PORT)
c = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
c.connect(addr) #連線伺服器
def putfile():
data = c.recv(1024)
print(str(data,encoding="utf8"))
file = input("請輸入檔案和路徑:")
filename = file.split("\\")[-1]
c.send(bytes(filename,encoding="gbk"))
with open(file,"rb") as f:
fdata = f.read()
c.send(fdata)
data2 = c.recv(1024)
print(str(data2,encoding="utf8"))
def getfile():
data = c.recv(1024) #接收對方的準備資訊
print(str(data,encoding="utf8")) #列印
file = input("請輸入對方的檔案和路徑:")
c.send(bytes(file,encoding="gbk")) #傳送檔名和路徑
filename = file.split("/")[-1] #獲取檔名
fdata = c.recv(20480) #準備接收檔案資料
with open(filename,"wb") as f:
f.write(fdata) #建立檔案
data2 = c.recv(1024) #接收完成迴應訊息
print(str(data2,encoding="utf8"))
def main(addr):
while True:
cmd = input("請輸入命令:")
c.send(bytes(cmd,encoding="gbk")) #將命令轉換後傳送
if cmd == "byebye": #如果傳送byby就退出連線
break
if cmd == "wycf":
putfile()
continue
if cmd == "wysf":
getfile()
continue
ret = c.recv(20480)
#print(str(ret,encoding="gbk"))
print(str(ret,encoding="utf8")) #收到的資訊顯示
c.close()
if __name__ == "__main__":
main(addr)