You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
1.5 KiB
62 lines
1.5 KiB
import telnetlib |
|
import sys |
|
|
|
HOST = "192.168.10.100" |
|
PORT = 23 |
|
USERNAME = "root" |
|
PASSWORD = "root" |
|
|
|
def main(argv): |
|
host = HOST |
|
port = PORT |
|
username = USERNAME |
|
passwd = PASSWORD |
|
if len(argv) > 2 : |
|
host = argv[1] |
|
port = argv[2] |
|
if len(argv) > 4: |
|
username = str(argv[3]) |
|
passwd = str(argv[4]) |
|
# 创建 Telnet 对象并连接远程主机 |
|
tn = telnetlib.Telnet(host, port) |
|
print(tn.host) |
|
|
|
# 匹配登录提示并发送用户名 |
|
tn.read_until(b"login: ") |
|
tn.write(username.encode('ascii') + b"\r\n") |
|
|
|
# 匹配密码提示并发送密码 |
|
tn.read_until(b"Password: ") |
|
tn.write(passwd.encode('ascii') + b"\r\n") |
|
|
|
# 匹配登录后的提示符 |
|
prompt = "#" |
|
match_index, _, _ = tn.expect([prompt.encode('ascii')], timeout=5) |
|
|
|
# 判断是否成功匹配 |
|
if match_index != -1: |
|
print("登录成功!") |
|
else: |
|
print("登录失败!") |
|
return -1 |
|
|
|
# 连接成功后,可以继续与远程主机进行交互 |
|
# 例如,发送命令并接收输出 |
|
tn.write(b"reboot\r\n") |
|
try: |
|
command_output = b"" |
|
while True: |
|
line = tn.read_until(b"\n") |
|
command_output += line |
|
if b"expected_output" in line: |
|
break |
|
print(command_output.decode("utf-8")) |
|
except Exception as e: |
|
print(e) |
|
|
|
# 关闭 Telnet 连接 |
|
tn.close() |
|
return 0 |
|
|
|
if __name__ == "__main__": |
|
main(sys.argv) |