使用python ssh运行本地shell脚本到远程

时间:2012-06-04 09:34:53

标签: python ssh paramiko

我很抱歉我的英语不好。 我有一天会在我的问题中搜索解决方案,但找不到。

这是我的问题: 我在服务器A中有一些管理器shell脚本。 我用

ssh username@other_server_ip < shell_script.sh

运行正常。

我想在python中这样做。 我测试了这个:

1\paramiko, 'exec_command (str)' is only run ONE command.and i use stdin to invoke_shell,not ok
2\pexect,sendline() is only ONE command.

请帮助我,谢谢!

(有些AIX不支持sft,所以我不想将sftp脚本用于其他服务器。)

像这样的shell脚本:

#!/bin/sh
if [ $# -lt 1 ]
os=`uname`
if [ "$os" = "linux" ] || [ "$os" = "Linux" ]
then
  temp=`df -P $diskname| tail -1`
  if [ "$temp" = "" ]
  then
    echo "error!t=$diskname not found"
    exit 0
  fi
  # diskutil=`echo $temp|awk '{printf("%s",$5)}'|awk '{gsub("%",""); print $0}'`
  disk_size=`echo $temp | awk '{print $2}'`
  disk_size_mb=`expr $disk_size / 1024`
  disk_size=`echo | awk '{ printf("%.2f",(c1/1024.0)) }' c1=$disk_size_mb`
  disk_size="${disk_size}"

elif [ "$os" = "SunOS" ]
then
  temp=`df -k $diskname | tail -1`
  ....

elif [ "$os" = "AIX" ] || [ "$os" = "aix" ]
then
  temp=`df -k $diskname |tail -1|sed -e "s/%//g"`
  ....
else 
  echo "error!!=Unsupported platform: $os"
  exit
fi

echo "Total Size=$disk_size_mb"

1 个答案:

答案 0 :(得分:0)

如果只是从Python触发脚本就足够了,请使用标准库中的subprocess.call。从查看脚本开始,我猜它是在多个远程主机上运行的,可能并行运行。您可能想看一下优秀的fabric模块。它是paramiko的包装器,它极大地方便了本地和远程运行命令以及上下传输文件。

相关问题