怎么用python做一个连接虚拟机的剪切板

  • Post author:
  • Post category:python




用python实现虚拟机的剪切板

主要用到的知识是socket通信

首先是客户端,可以是你的电脑,也可以是虚拟机

import socket

#建立套接字
class server():
    def __init__(self):
       address = ("192.128.0.106", 5005)
       self.fuwu = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
       self.fuwu.bind(address)
       self.fuwu.listen()
       self.conn, self.addr = self.fuwu.accept()
       print("{} + connect OK!".format(self.addr))
       print("不输入结束会话退出程序")

    #把要复制的东西放在剪切板中
    def data_in(self):
        with open("sharing.txt",'w',encoding="utf-8") as f:
            while True:
                try:
                    f.write(input(""))
                    f.write("\n")
                except EOFError:
                    f.close()
                    break
    #发送给另一个客户机
    def send(self):
        with open("sharing.txt",'r',encoding = "utf-8") as file:
            for i in file.readlines():
                self.conn.sendall(i.encode())
    def __del__(self):
        self.conn.close()
        self.fuwu.close()

sever1 = server()
sever1.data_in()
sever1.send()

接下来是客户机

import socket
import sys



class client():
    def __init__(self):
        address = ("192.168.0.106", 5005)
        self.upsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            self.upsock.connect(address)
        except:
            print("ERROR connecion")
            sys.exit()
        print("=+= connnect OK! =+=")
        print("输出剪切板:\n")

    #接收剪切板
    def recive(self):
        while True:
            recvit = self.upsock.recv(1024)
            print(recvit.decode())
            if not recvit:
                print("感谢使用")
                break
            # try:
            #     send = input("")
            #     upsock.sendall(send.encode())
            # except EOFError:
            #     break
    def __del__(self):
        self.upsock.close()


client1 = client()
client1.recive()

注意虚拟机不好连,可以用主机,且address是你的ip加端口,可以是5000-10000等等



版权声明:本文为vegetablird原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。