• Python Socke


    回射

    SERVER

    #!/usr/bin/python3
    #_*_ coding:utf-8 _*_
    
    import socket,os,time
    import  socketserver
    import time
    import threading
    import random
    import sys
    import socket
    import getopt
    import os
    import re
    import shutil
    import platform
    
    class ServerHandle(socketserver.BaseRequestHandler):
    
        def handle(self):
    
            conn = self.request
            conn.sendall(bytes("Hello I'm robot!",encoding="utf-8"))
            while True:
                ret_bytes = conn.recv(1024)
                ret_str = str(ret_bytes,encoding="utf-8")
                if ret_str == "q":
                    break
                conn.sendall(bytes("You Send:" + ret_str,encoding="utf-8"))
    
    def daemonize(stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
        pid = os.fork()
        if pid > 0:
            sys.exit(0)
    
        os.chdir("/")
        os.umask(0)
        os.setsid()
    
        pid = os.fork()
        if pid > 0:
            sys.exit(0)
    
        for f in sys.stdout, sys.stderr: f.flush()
        si = open(stdin, 'r')
        so = open(stdout, 'a+')
        #se = open(stderr, 'a+', 0)
        os.dup2(si.fileno(), sys.stdin.fileno())
        os.dup2(so.fileno(), sys.stdout.fileno())
        #os.dup2(se.fileno(), sys.stderr.fileno())
    
    
    
    if __name__ == "__main__":
        daemonize('/dev/null', '/home/share/kitking/stdout.log', '/home/share/kitking/error.log')
        server = socketserver.ThreadingTCPServer(("192.168.199.XXX",6969),ServerHandle)
        server.serve_forever()

    CLIENT

    #!/usr/bin/python3
    #_*_ coding:utf-8 _*_
    
    import socket,os,time
    import  socketserver
    
    host = "XXX.eicp.net"
    ip = socket.gethostbyname(host)
    port = 6969
    
    obj = socket.socket()
    obj.connect((ip,port))
    
    ret_bytes = obj.recv(1024)
    ret_str = str(ret_bytes,encoding="utf-8")
    print(ret_str)
    
    while True:
        inp = input(">>")
        if inp == "q":
            obj.sendall(bytes(inp,encoding="utf-8"))
            break
        else:
            obj.sendall(bytes(inp, encoding="utf-8"))
            ret_bytes = obj.recv(1024)
            ret_str = str(ret_bytes,encoding="utf-8")
            print(ret_str)

    SSH模拟

    SERVER

    import socket,os,time
    server = socket.socket()
    server.bind(('localhost',6969))
     
    server.listen()
     
    while True:
        print("beging waiting request...")
        conn,addr = server.accept()
        print("new conn:",addr)
        while True:
            print("request comming!",addr)
            data = conn.recv(1024)
            if not data:
                print("客户端已断开")
                break
            print("执行指令:",data)
            cmd = data.decode()
            cmd_res = os.popen(cmd).read()
            print("before send",len(cmd_res.encode('utf-8')))
            if len(cmd_res) == 0:
                com_res = "cmd has no output..."
            conn.send(str(len(cmd_res.encode('utf-8'))).encode('utf-8'))
            #time.sleep(0.5)
            client_ack = conn.recv(1024) #wait client confirm
            conn.send(cmd_res.encode("utf-8"))
            print("send done")
    server.close()

    CLIENT

    import socket
    client = socket.socket()
    client.connect(('localhost',6969))
     
    while True:
        cmd = input(">>").strip()
        if len(cmd) == 0:continue
        client.send(cmd.encode("utf-8"))
        cmd_res_size = client.recv(1024)
        client.send(b"start_trans")
        sev_file_size = int(cmd_res_size.decode())
        #print('sev_file_size',sev_file_size,type(sev_file_size))
        received_size = 0
        received_data = b''
     
        while received_size < sev_file_size:
            data = client.recv(1024)
            #print("收到数据!")
            received_size += len(data)
            received_data += data
            #print('cli_file_size',received_data)
        else:
            #print("receive done...",received_size)
            print(received_data.decode())
     
    client.close()

    文件传送

    SERVER

    import socket,os,time,hashlib
    server = socket.socket()
    server.bind(('localhost',6969))
     
    server.listen()
     
    while True:
        print("beging waiting request...")
        conn,addr = server.accept()
        print("new conn:",addr)
        while True:
            print("request comming!",addr)
            data = conn.recv(1024)
            if not data:
                print("客户端已断开")
                break
            cmd,filename = data.decode().split()
            if os.path.isfile(filename):
                f = open(filename,'rb')
                m = hashlib.md5()
                file_size = os.stat(filename).st_size
                conn.send(str(file_size).encode('utf-8')) #send file size
                conn.recv(1024)  #wait for ack
                for line in f:
                    m.update(line)
                    conn.send(line)
                print("file md5",m.hexdigest())
                f.close()
                conn.send(m.hexdigest().encode())
     
     
            print("send done")
    server.close()

    CLIENT

    import socket,hashlib
    client = socket.socket()
    client.connect(('localhost',6969))
     
    while True:
        cmd = input(">>").strip()
        if len(cmd) == 0:continue
        if cmd.startswith('get'):
            client.send(cmd.encode('utf-8'))
            server_response = client.recv(1024)
            print('server response:',server_response)
            client.send(b'start to trans')
            file_total_size = int(server_response.decode())
            received_size = 0
            file_name = cmd.split()[1]
            f = open(file_name+".new",'wb')
            m = hashlib.md5()
            while received_size < file_total_size:
                if file_total_size - received_size >= 1024:
                    size = 1024
                else:
                    size = file_total_size - received_size
                data = client.recv(size)
                received_size += len(data)
                m.update(data)
                f.write(data)
                #print(file_total_size,received_size)
            else:
                new_file_md5 = m.hexdigest()
                print("file recv done",received_size,file_total_size)
                f.close()
            server_file_md5 = client.recv(1024)
            print("server file md5:",server_file_md5)
            print('client file md5:',new_file_md5)
     
     
     
    client.close()

    FTP模式

    SERVER

    import socket,hashlib
    import socketserver,json,os
     
    class MyTCPHandler(socketserver.BaseRequestHandler):
     
        def put(self,*args):
            cmd_dic = args[0]
            filename = cmd_dic['filename']
            filesize = cmd_dic['filesize']
            if os.path.isfile(filename):
                f = open(filename + ".new",'wb')
            else:
                f = open(filename,'wb')
            self.request.send(b'200,ok')
            recived_size = 0
            m = hashlib.md5()
            while recived_size < filesize:
                data = self.request.recv(1024)
                m.update(data)
                f.write(data)
                recived_size += len(data)
            else:
                f.close()
                print("file [%s] has uploaded..."%filename)
                recived_md5 = m.hexdigest()
                source_md5 = self.request.recv(1024).decode()
                if recived_md5 == source_md5:
                    self.request.send('MD5校验成功'.encode('utf-8'))
                else:
                    self.request.send('MD5校验失败'.encode('utf-8'))
     
     
     
     
     
        def handle(self):
            while True:
                try:
                    print("开始监听!")
                    self.data = self.request.recv(1024).strip()
                    print("{} wrote:".format(self.client_address[0]))
                    print(self.data)
                    if not self.data:
                        print(self.client_address,"断开了!")
                        break
                    cmd_dic = json.loads(self.data.decode())
                    action = cmd_dic['action']
                    if hasattr(self,action):
                        func = getattr(self,action)
                        func(cmd_dic)
     
     
     
     
                except ConnectionRefusedError as e:
                    print(e)
                    break
     
     
    if __name__ == "__main__":
        HOST,PORT="localhost",9999
        server = socketserver.ThreadingTCPServer((HOST,PORT),MyTCPHandler)
        server.serve_forever()

    CLIENT

    import socket
    import os,json
    import hashlib
     
     
     
    class FtpClient(object):
        def __init__(self):
            self.client = socket.socket()
     
        def cmd_help(self,args):
            msg = '''
            ls
            pwd
            cd
            get filename
            put filename
            '''
            print(msg)
     
        def connect(self,ip,port):
            self.client.connect((ip,port))
     
        def interactive(self):
            self.auth()
            while True:
                cmd = input(">>").strip()
                if len(cmd) == 0:continue
                cmd_str = cmd.split()[0]
                if hasattr(self,'cmd_%s'%cmd_str):
                    func = getattr(self,'cmd_%s'%cmd_str)
                    func(cmd)
                else:
                    self.help()
     
     
     
        def cmd_put(self,*args):
            cmd_split = args[0].split()
            if len(cmd_split) > 1:
                filename = cmd_split[1]
                os.path.isfile(filename)
                filesize = os.stat(filename).st_size
                msg_dic = {
                    'action': 'put',
                    'filename': filename,
                    'filesize': filesize,
                    'overridden': True
                }
                self.client.send(json.dumps(msg_dic).encode('utf-8'))
                server_response = self.client.recv(1024)
                f = open(filename,'rb')
                m = hashlib.md5()
                for line in f:
                    m.update(line)
                    self.client.send(line)
                else:
                    print("file upload success...")
                f.close()
                self.client.send(m.hexdigest().encode())
                sev_md5_check = self.client.recv(1024)
                print(sev_md5_check.decode())
            else:
                print('file is not exist')
     
        def cmd_get(self):
            pass
     
     
        def auth(self):
            pass
     
     
     
    class Account(object):
        def __init__(self):
            pass
     
     
     
    ftp = FtpClient()
    ftp.connect('localhost',9999)
    ftp.interactive()

    上传文件

    import socket
    
    sk = socket.socket()
    
    sk.bind(("127.0.0.1",8080))
    sk.listen(5)
    
    while True:
        conn,address = sk.accept()
        conn.sendall(bytes("欢迎光临我爱我家",encoding="utf-8"))
    
        size = conn.recv(1024)
        size_str = str(size,encoding="utf-8")
        file_size = int(size_str)
    
        conn.sendall(bytes("开始传送", encoding="utf-8"))
    
        has_size = 0
        f = open("db_new.jpg","wb")
        while True:
            if file_size == has_size:
                break
            date = conn.recv(1024)
            f.write(date)
            has_size += len(date)
    
        f.close()
    
    客户端
    
    import socket
    import os
    
    obj = socket.socket()
    
    obj.connect(("127.0.0.1",8080))
    
    ret_bytes = obj.recv(1024)
    ret_str = str(ret_bytes,encoding="utf-8")
    print(ret_str)
    
    size = os.stat("yan.jpg").st_size
    obj.sendall(bytes(str(size),encoding="utf-8"))
    
    obj.recv(1024)
    
    with open("yan.jpg","rb") as f:
        for line in f:
            obj.sendall(line)
  • 相关阅读:
    repadmin example.
    在 Windows 2000 和 Windows XP 中重置计算机帐户
    管理活动目录
    使用AdsiEdit工具查看GC数据
    mms链接media player 9.0无法打开
    活动目录的复制之细节
    使用Repadmin.exe 对活动目录复制排错
    Difference among Domain Local Group and Global Group and Universal Group
    使用 ADSI Edit 编辑 Active Directory 属性
    xp的密码工具
  • 原文地址:https://www.cnblogs.com/jiangzhaowei/p/9269438.html
Copyright © 2020-2023  润新知