python代码ssh自动连接ubuntu

来源:互联网 发布:淘宝宝贝详情图模板 编辑:程序博客网 时间:2024/04/30 14:54
import getpassimport socketimport termiosimport sysimport tracebackimport ttyimport paramikofrom paramiko.py3compat import udef posix_shell(chan):    import select    oldtty = termios.tcgetattr(sys.stdin)    try:        tty.setraw(sys.stdin.fileno())        tty.setcbreak(sys.stdin.fileno())        chan.settimeout(0.0)        while True:            r, w, e = select.select([chan, sys.stdin], [], [])            if chan in r:                try:                    x = u(chan.recv(1024))                    if len(x) == 0:                        sys.stdout.write('\r\n*** EOF\r\n')                        break                    sys.stdout.write(x)                    sys.stdout.flush()                except socket.timeout:                    pass            if sys.stdin in r:                x = sys.stdin.read(1)                if len(x) == 0:                    break                chan.send(x)    finally:        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)def connect(hostname, port, username, password):    try:        client = paramiko.SSHClient()        client.load_system_host_keys()        client.set_missing_host_key_policy(paramiko.WarningPolicy())        print('*** Connecting...')        try:            client.connect(hostname, port, username, password)        except Exception:            password = getpass.getpass('Password for %s@%s: ' % (username, hostname))            client.connect(hostname, port, username, password)        chan = client.invoke_shell()        print(repr(client.get_transport()))        print('*** Here we go!\n')        posix_shell(chan)        chan.close()        client.close()    except Exception as e:        print('*** Caught exception: %s: %s' % (e.__class__, e))        traceback.print_exc()        try:            client.close()        except:            pass        sys.exit(1)
需要paramiko的支持
0 0
原创粉丝点击