SSH and telnet to localhost using python

前端 未结 1 969
悲&欢浪女
悲&欢浪女 2021-01-20 19:50

I am new to python and if the question is very nooby i apologize. Simply put i need to write a script that connects to remote via ssh then telnets to localhost and execute a

相关标签:
1条回答
  • 2021-01-20 20:06

    after a simple search:

    telnet: link

    import getpass
    import sys
    import telnetlib
    
    HOST = "hostname"
    
    user = raw_input("Enter your remote account: ")
    
    password = getpass.getpass()
    
    tn = telnetlib.Telnet(HOST)
    
    tn.read_until("login: ")
    
    tn.write(user + "\n")
    
    if password:
        tn.read_until("Password: ")
        tn.write(password + "\n")
    
    tn.write("ls\n")
    
    tn.write("exit\n")
    
    print tn.read_all()
    

    ssh: link

    import pxssh
    import getpass
    try:                                                            
        s = pxssh.pxssh()
        hostname = raw_input('hostname: ')
        username = raw_input('username: ')
        password = getpass.getpass('password: ')
        s.login (hostname, username, password)
        s.sendline ('uptime')   # run a command
        s.prompt()             # match the prompt
        print s.before          # print everything before the prompt.
        s.sendline ('ls -l')
        s.prompt()
        print s.before
        s.sendline ('df')
        s.prompt()
        print s.before
        s.logout()
    except pxssh.ExceptionPxssh, e:
        print "pxssh failed on login."
        print str(e)
    
    0 讨论(0)
提交回复
热议问题