Python 使用/不使用密码通过telnet进行各种连接 导入telnetlib 导入操作系统 进口稀土 当前目录=os.getcwd() IP= def登录为root(): 打印“以root用户身份登录…” tn.read_直到(“登录:”) tn.write(“root\r”) response=tn.expect([re.compile(b“Password:”)、b“root@、])) 如果响应[2]中出现“密码”: 发送消息(“根”,“根@”) 其他: 打印“不带密码的日志记录” def发送消息(消息,等待消息,打印消息=0): 如果打印消息: 打印味精 tn.write(“%s\n”%msg) 返回tn.read\u直到(等待) def启动_更新(): 尝试: 打印发送消息(“装载-重新装载,rw/”,“根@”,打印消息=1) 除: 异常(“更新配置失败”) def main(): 全球总氮 尝试: tn=telnetlib.Telnet(IP) 以root()身份登录 除: 引发异常(“连接失败”) 启动更新() 如果名称=“\uuuuu main\uuuuuuuu”: main()

Python 使用/不使用密码通过telnet进行各种连接 导入telnetlib 导入操作系统 进口稀土 当前目录=os.getcwd() IP= def登录为root(): 打印“以root用户身份登录…” tn.read_直到(“登录:”) tn.write(“root\r”) response=tn.expect([re.compile(b“Password:”)、b“root@、])) 如果响应[2]中出现“密码”: 发送消息(“根”,“根@”) 其他: 打印“不带密码的日志记录” def发送消息(消息,等待消息,打印消息=0): 如果打印消息: 打印味精 tn.write(“%s\n”%msg) 返回tn.read\u直到(等待) def启动_更新(): 尝试: 打印发送消息(“装载-重新装载,rw/”,“根@”,打印消息=1) 除: 异常(“更新配置失败”) def main(): 全球总氮 尝试: tn=telnetlib.Telnet(IP) 以root()身份登录 除: 引发异常(“连接失败”) 启动更新() 如果名称=“\uuuuu main\uuuuuuuu”: main(),python,telnet,telnetlib,Python,Telnet,Telnetlib,需要以\u root()身份登录的帮助。以root用户身份登录有两种情况:使用密码和不使用任何密码。我必须正确连接到主机,然后在launch_update()中启动几个命令。在mount命令后,脚本将停止。根@是否应该有最后的空间?删除空间会有所帮助。我真的不明白为什么,因为我只将登录名改为\u root(),在该脚本正常工作之前。谢谢大家!launch\u update希望会话提示符以“root@”开头。如果以前是这样,那么可能是旧的login\u as\u root设置了PS1环境变量,该变

需要以\u root()身份登录的帮助。以root用户身份登录有两种情况:使用密码和不使用任何密码。我必须正确连接到主机,然后在launch_update()中启动几个命令。在mount命令后,脚本将停止。

根@
是否应该有最后的空间?删除空间会有所帮助。我真的不明白为什么,因为我只将登录名改为\u root(),在该脚本正常工作之前。谢谢大家!
launch\u update
希望会话提示符以“root@”开头。如果以前是这样,那么可能是旧的
login\u as\u root
设置了
PS1
环境变量,该变量控制提示符的外观。那只是猜测而已!
import telnetlib
import os
import re

current_dir = os.getcwd()
IP = <IP>

def login_as_root():

    print "logging in as root..."
    tn.read_until("login: ")
    tn.write("root\r")
    response = tn.expect([re.compile(b"Password:"),b"root@",])
    if "Password:" in response[2]:
        send_msg("root", "root@")
    else:
        print "logging without passwd"

def send_msg(msg, wait_str, print_msg=0):
    if print_msg:
        print msg
    tn.write("%s\n" % msg)
    return tn.read_until(wait_str)

def launch_update():
    try:
        print send_msg("mount -o remount,rw /", "root@ ", print_msg=1)
    except:
        Exception("Update configuring is failed")

def main():
    global tn
    try:
        tn = telnetlib.Telnet(IP)
        login_as_root()
    except:
        raise Exception("Connect failed")

    launch_update()

if __name__ == "__main__":
    main()