我这里的需求是:获取当前系统的IP地址,并将结果写入到远程服务器中。
代码如下:
#!/usr/bin/env python
# -*-coding:utf-8-*-
import socket, paramiko
def get_ipAddress():
st = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# st.connect(('10.255.255.255', 1))
st.connect(('8.8.8.8', 80))
IP = st.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
st.close()
return IP
ipaddress = get_ipAddress()
print(ipaddress)
# ip、用户名、密码
ip = ""
port = 22
user = "root"
password = "install"
# 创建SSHClient 实例对象
ssh = paramiko.SSHClient()
# 调用方法,表示没有存储远程机器的公钥,允许访问
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接远程机器,地址,端口,用户名密码
ssh.connect(ip, port, user, password, timeout=10)
stdin, stdout, stderr = ssh.exec_command("echo " + ipaddress + " >> /storage/lm/add.txt")
print(stdout)