2019년 2월 23일 토요일

[Python] Network Library Wrappers


pynet.py

1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
######################################################################
# HTTP Library
######################################################################

import os
import select
def readTimeout(f):
    data = None
    while True:
        r, w, e = select.select([ f ], [], [], 0)
        if f in r:
            data = os.read(f.fileno())
            break
    return data;
    
######################################################################
# HTTP Library
######################################################################

import http.client, urllib.parse

def httpGet(url):
    conn = http.client.HTTPSConnection(url)
    conn.request("GET", "/")
    rv = conn.getresponse()
    data = None
    if rv.status == 200 or rv.reason == "OK":
        data = rv.read()
    '''
    conn.request("GET", "/")
    rv = conn.getresponse()
    while not rv.closed:
        print(rv.read(200))
    conn.close()
    '''
    return rv, data
    
def httpProxyGet(proxyaddr, proxyport, url):
    conn = http.client.HTTPSConnection(proxyaddr, proxyport)
    conn.set_tunnel(url)
    conn.request("GET", "/")
    rv = conn.getresponse()
    data = None
    if rv.status == 200 or rv.reason == "OK":
        data = rv.read()
    conn.close()
    return rv, data

def httpPost(url):
    params = urllib.parse.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})
    headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
    conn = http.client.HTTPConnection(url)
    conn.request("POST", "", params, headers)
    rv = conn.getresponse()
    data = None
    if rv.status == 200 or rv.reason == "OK":
        data = rv.read()
    conn.close()
    return rv, data

######################################################################
# Telnet Library
######################################################################

import getpass
import sys
import telnetlib

class pytelnet():
    def __init__(host,user,passwd):
        self.tn = telnetlib.Telnet(host.encode('utf-8'))
        self.tn.read_until(b"login: ")
        self.tn.write(user.encode('utf-8') + b"\n")
        self.tn.read_until(b"Password: ")
        self.tn.write(passwd.encode('utf-8') + b"\n")

    def write(s):
        self.tn.write(s.encode('utf-8'))
        
    def readall():
        return tn.read_all().decode("utf-8")

######################################################################
# FTP Library
######################################################################
from ftplib import FTP
class pyftp():
    def __init__(self,host,user,passwd):
        self.ftp = FTP(host)     # connect to host, default port
        self.ftp.login(user,passwd)  
        
    def close(self):
        return self.ftp.quit()
        
    def pasv(self):
        return self.ftp.set_pasv(True)
        
    def cd(self,path):
        return self.ftp.cwd(path)
        
    def ls(self):
        return self.ftp.retrlines('LIST')

    def get(self,remote,local):
        return self.ftp.retrbinary('RETR ' + remote, open(local, 'wb').write)
        
    def put(self,local,remote):
        return self.ftp.storbinary('STOR ' + remote, open(local, 'rb'))
    
######################################################################
# FTPD Library : pip install pyftpdlib
######################################################################  
#import pyftpdlib as ftpd
#Read permissions:
#    - "e" = change directory (CWD command)
#    - "l" = list files (LIST, NLST, STAT, MLSD, MLST, SIZE, MDTM commands)
#    - "r" = retrieve file from the server (RETR command)
#
#Write permissions:
#    - "a" = append data to an existing file (APPE command)
#    - "d" = delete file or directory (DELE, RMD commands)
#    - "f" = rename file or directory (RNFR, RNTO commands)
#    - "m" = create directory (MKD command)
#    - "w" = store a file to the server (STOR, STOU commands)
#    - "M" = change file mode (SITE CHMOD command)
#    - "T" = update file last modified time (MFMT command)
# read_perms = "elr"
# write_perms = "adfmwMT"

#CRITICAL = 50
#FATAL = CRITICAL
#ERROR = 40
#WARNING = 30
#WARN = WARNING
#INFO = 20
#DEBUG = 10
#NOTSET = 0

import logging
class logHandler(logging.Handler):
    terminator = '\n'
    def __init__(self, stream=None):
        logging.Handler.__init__(self)
    def flush(self):
        pass
    def emit(self, record):
        msg = self.format(record)
        print( 'PYLOG:' + msg)
        #print(self.terminator)
        self.flush()
    def __repr__(self):
        return "PYLOG"

def runFtpServer():
    from pyftpdlib.authorizers import DummyAuthorizer
    from pyftpdlib.handlers import FTPHandler
    from pyftpdlib.servers import FTPServer
    
    authorizer = DummyAuthorizer()
    authorizer.add_user("user", "12345", "D:/Temp", perm="elradfmwMT")
    authorizer.add_anonymous("D:/Temp1")
    
    handler = FTPHandler
    handler.authorizer = authorizer
    
    server = FTPServer(("127.0.0.1", 21), handler)

    #formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    #ch.setFormatter(formatter)
    logger = logging.getLogger('pyftpdlib')
    logger.setLevel(logging.INFO)
    logger.addHandler(logHandler())

    server.serve_forever()
    
######################################################################
# SSH Library
######################################################################   
import paramiko
def sshCommand(host,user,passwd,command):
    ssh = paramiko.SSHClient()
    #ssh.load_system_host_keys(filename='/home/barashe/.ssh/known_hosts')
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(host, username=user, password=passwd)
    return ssh.exec_command(command) #in, out, err
    
class pyssh():
    def __init__(self,host,user,passwd):
        self.ssh = paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh.connect(host, username=user, password=passwd)
        self.passwd = passwd

    def close(self):
        self.ssh.close()
        
    def execute(self,cmd):
        return self.ssh.exec_command(cmd) #in, out, err
    
    def sudo_execute(self,cmd):
        stdin, stdout, stderr = self.ssh.exec_command('sudo ' + cmd)
        stdin.write( self.passwd.encode('utf-8') + b'\n')
        stdin.flush()
        return stdin, stdout, stderr
    
class pysftp():    
    def __init__(self,host,user,passwd):
        self.trans = paramiko.Transport((host,22))
        self.trans.connect(username=user,password=passwd)
        self.sftp = paramiko.SFTPClient.from_transport(self.trans) 

    def put(self,local,remote):
        return self.sftp.put(local,remote)

    def get(self,remote,local):
        return self.sftp.get(remote,local)
        
#import spur
#def sshCommand2(host,user,passwd,command):
#    shell = spur.SshShell(hostname=host, username=user, password=passwd)
#    result = shell.run(["ls", "-l"])

######################################################################
# Test Code
######################################################################
def httpProxyGetTest():
    rv, data = httpProxyGet("proxy.com", 8080,"www.python.org")
    print( data )
    print( rv.status, rv.reason )
    
def ftpTest():
    ftp = pyftp(sys.argv[1],sys.argv[2],sys.argv[3])
    ftp.pasv()
    print(ftp.ls())
    print(ftp.get("a.c","D:/Temp/aaaa.c"))
    print(ftp.put("D:/Temp/aaaa.c","bbbb.c"))
    
def sshTest():
    ssh = pyssh(sys.argv[1],sys.argv[2],sys.argv[3])
    ins, outs, errs = ssh.execute("ls -l")
    while True:
        data = outs.read(10)
        if not data:
            break;
        print( data );
    ins, outs, errs = ssh.execute("pwd")
    print( outs.read() );
    
def sshSudoTest():
    ssh = pyssh(sys.argv[1],sys.argv[2],sys.argv[3])
    ins, outs, errs = ssh.sudo_execute("ls -l")
    print( outs.read() );
    
def sftpTest():
    sftp = pysftp(sys.argv[1],sys.argv[2],sys.argv[3])
    rv = sftp.put("D:/temp/line.png", "line.png")
    print(rv)
    rv = sftp.get("line.png", "D:/temp/line_200.png")
    print(rv)
    
######################################################################
# Main
######################################################################
if __name__ == "__main__":
    print( len(sys.argv), sys.argv )
    #httpProxyGetTest()
    #sshTest()
    #sftpTest()
    #ftpTest()
    runFtpServer()

댓글 없음:

댓글 쓰기