我想在python中使用fabric,在远程服务器上执行命令。
我写了这些:
from fabric.api import *
from fabric.tasks import execute
def do_some_thing():
run("ls -lh")
if __name__ == '__main__':
execute(do_some_thing,hosts=['root@10.18.103.102'])
但是,它不起作用并让我登录..
这是输出:
➜ ~ python test.py
[root@10.18.103.102] Executing task 'do_some_thing'
[root@10.18.103.102] run: ls -lh
[root@10.18.103.102] out: root@svn:~#
[root@10.18.103.102] out: root@svn:~#
答案 0 :(得分:1)
使用env
变量 -
from fabric.api import *
from fabric.contrib.files import *
def myserver():
env.hosts = ['10.18.103.102']
env.user = 'root'
# if you have key based authentication, uncomment and point to private key
# env.key_filename = '~/.ssh/id_rsa'
# if you have password based authentication
env.password = 'ThEpAsAwOrd'
def ls():
run('ls -al')
现在将它们保存在文件调用fabfile.py
中并执行(在同一目录下) -
$ fab myserver ls
Fabric将一个接一个地执行这两个功能。因此,当它执行ls()
时,它将在env
中包含服务器详细信息。