最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】fabric 2中如何在远程服务器中基于cd切换路径后再执行命令

命令 crifan 1058浏览 0评论
折腾:
【未解决】Fabric 2中如何实现Fabric 1中的rsync_project去实现同步代码以实现项目代码部署
期间,需要先去搞清楚:
如何在Fabric 2中,用Connection连接远程服务器后,cd目录后,执行新的命令, 比如pwd
参考之前Fabric 1:
用 Fabric 实现自动化部署 – 李林克斯
Python远程部署利器Fabric详解 – Python – 伯乐在线
from fabric.api import env, cd, put
env.hosts = ['
[email protected]
', ]
env.password = '111111'
def hello():
    with cd('/var/www/'):
        put('/tmp/myapp-0301.tar.gz', 'myapp.tar.gz')
cd后,好像需要用with,然后才可以针对于新目录操作
试了试:
@task
def deploy(context):
    remoteConn = Connection(host=RemoteHost, user=RemoteUser)
    # print(remoteConn)
    seperatorLine()
    print("Following command run in local:")
    context.run('pwd')
    # context.run('ls')
    seperatorLine()
    print("Following command run in remote server:")
    remoteConn.run('uname -a')
    remoteConn.run('pwd')
    remoteConn.run('ls')
    with remoteConn.run('cd %s' % RemotePathRoot):
        remoteConn.run('pwd', echo=True)
结果出错:
Traceback (most recent call last):
  File "/Users/crifan/Library/Python/2.7/bin/fab", line 11, in <module>
    sys.exit(program.run())
  File "/Users/crifan/Library/Python/2.7/lib/python/site-packages/invoke/program.py", line 335, in run
    self.execute()
  File "/Users/crifan/Library/Python/2.7/lib/python/site-packages/invoke/program.py", line 491, in execute
    executor.execute(*self.tasks)
  File "/Users/crifan/Library/Python/2.7/lib/python/site-packages/invoke/executor.py", line 129, in execute
    result = call.task(*args, **call.kwargs)
  File "/Users/crifan/Library/Python/2.7/lib/python/site-packages/invoke/tasks.py", line 128, in __call__
    result = self.body(*args, **kwargs)
  File "/Users/crifan/Downloads/fabfile.py", line 24, in deploy
    with remoteConn.run('cd %s' % RemotePathRoot):
AttributeError: __exit__
好像:
Frequently Asked/Answered Questions (FAQ) — Fabric documentation
中有解释?
需要自己把:
@task
def deploy(c):
    c.run("cd /path/to/application")
    c.run("./update.sh")
改为:
def deploy(c):
    c.run("cd /path/to/application && ./update.sh")
此处改为:
remoteConn.run('cd %s && pwd && ls -lha' % RemotePathRoot)
输出:
/root/xxx_20180101/nlp/test_fabric
total 12K
drwxr-xr-x 2 root root 4.0K Aug 17 13:56 .
drwxr-xr-x 5 root root 4.0K Aug 17 13:52 ..
-rw-r--r-- 1 root root 2.7K Aug 17 16:41 fabfile.py
【总结】
Fabric 2中,不直接支持远端cd后继续执行命令,因为:
每个Fabric的run都是一个独立的session
解决办法(不完美的workaround)是:
cd后的命令,改为 &&连接,比如:
remoteConn.run('cd /xxx/xxx && pwd && ls -lha')
要么是尽量不要cd,而使用绝对路径,比如:
c.run("/path/to/application/update.sh")

转载请注明:在路上 » 【已解决】fabric 2中如何在远程服务器中基于cd切换路径后再执行命令

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.171 seconds, using 21.84MB memory