以下是一个Python脚本的示例,它可以自动进行SSH登录服务器,通过端口9100进行打印机的Telnet连接,并运行两个命令。然后,它会重复执行该过程。
import paramiko
import time
def ssh_connect(hostname, port, username, password):
# 创建SSH客户端对象
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# 连接服务器
client.connect(hostname, port=port, username=username, password=password)
print("SSH连接成功")
# 创建Telnet连接
telnet_conn = client.invoke_shell()
# 发送Telnet命令
telnet_conn.send("telnet localhost 9100\n")
time.sleep(1)
# 运行两个命令
telnet_conn.send("command1\n")
time.sleep(1)
telnet_conn.send("command2\n")
time.sleep(1)
# 获取命令输出
output = telnet_conn.recv(65535)
print(output.decode("utf-8"))
# 关闭Telnet连接
telnet_conn.close()
except paramiko.AuthenticationException:
print("SSH认证失败")
except paramiko.SSHException as ssh_ex:
print("SSH连接错误: ", ssh_ex)
except paramiko.Exception as ex:
print("错误: ", ex)
finally:
# 关闭SSH连接
client.close()
if __name__ == "__main__":
# SSH连接信息
hostname = "your_hostname"
port = 22
username = "your_username"
password = "your_password"
# 重复执行SSH连接和Telnet操作
while True:
ssh_connect(hostname, port, username, password)
time.sleep(10)
请注意,上述示例中的一些信息需要根据您的实际情况进行更改,例如服务器的主机名、端口号、用户名和密码。此外,您还需要安装paramiko库来进行SSH连接。