- 论坛徽章:
- 0
|
本帖最后由 remyzane 于 2013-12-18 18:51 编辑
import subprocess
# 本机
p = subprocess.Popen('uptime', stdout=subprocess.PIPE)
# 远程服务器,需要配置youserver.com自动登录(通过密钥文件自动登录)
p = subprocess.Popen(['ssh', 'root@youserver.com', 'uptime'], stdout=subprocess.PIPE)
info = p.stdout.readline()
print(info) # 输出:b' 18:22:27 up 51 days, 1:47, 1 user, load average: 0.16, 0.03, 0.01\n'
上述方法适合于执行频率不高场合。如果执行频率很高,就需要在服务器上写独立的服务程序,并且建议直接用 python 的 psutil 模块读去CPU状态
# ===================================================================================
# ssh 自动登录配置方法:
# ===================================================================================
#==== 服务器上生成密钥对 ====
ssh-keygen -t rsa
> 全部默认(一路回车)
#==== 服务器上配置密钥对 ====
mv ~/.ssh/id_rsa.pub ~/.ssh/authorized_keys
mv ~/.ssh/id_rsa ~/.ssh/ids/self
chmod go-rwx ~/.ssh -R
#==== 配置ssh客户端 ====
vim ~/.ssh/config
IdentityFile ~/.ssh/ids/%h.%r
mkdir -p ~/.ssh/id
#==== 下载密钥到客户端 ====
scp root@youserver.com:.ssh/ids/self ~/.ssh/ids/youserver.com.root
chmod -R go-rwx ~/.ssh |
|