python - 如何使用 python 2.3 rsh ssh

标签 python python-2.3

我想编写一个执行以下 Linux 命令序列的脚本:

  1. rsh rr01(这里系统会要求输入密码)
  2. ssh rr02(此时系统会再次要求输入密码)
  3. 在某个文件上激活我的应用

我天真地(而且愚蠢地)试图用一个简单的 os.system 来实现这一点 请记住,我使用 python 2.3,并且希望避免添加模块(如果可能)。

提前致谢!

最佳答案

[编辑]还可以查看在 http://code.google.com/p/lexel-intern0t/source/browse/trunk/Python/ssh_client.py 上使用 paramiko 的另一个示例.

http://media.commandline.org.uk//code/ssh.txt 上找到的脚本可能会帮助你。它包括 os 模块(用于查找 key )和用于日志记录目的的 tempfile 模块,两者都可以在 python 2.3 全局模块索引( http://docs.python.org/release/2.3/modindex.html )和用于 SSH2 协议(protocol)实现的 paramiko( http://www.lag.net/paramiko/docs/ )中找到,该模块应该在 python 上工作2.3 及以上。这是一段简单的代码:

"""Friendly Python SSH2 interface."""

import os
import tempfile
import paramiko

class Connection(object):
    """Connects and logs into the specified hostname. 
    Arguments that are not given are guessed from the environment.""" 

    def __init__(self,
                 host,
                 username = None,
                 private_key = None,
                 password = None,
                 port = 22,
                 ):
        self._sftp_live = False
        self._sftp = None
        if not username:
            username = os.environ['LOGNAME']

        # Log to a temporary file.
        templog = tempfile.mkstemp('.txt', 'ssh-')[1]
        paramiko.util.log_to_file(templog)

        # Begin the SSH transport.
        self._transport = paramiko.Transport((host, port))
        self._tranport_live = True
        # Authenticate the transport.
        if password:
            # Using Password.
            self._transport.connect(username = username, password = password)
        else:
            # Use Private Key.
            if not private_key:
                # Try to use default key.
                if os.path.exists(os.path.expanduser('~/.ssh/id_rsa')):
                    private_key = '~/.ssh/id_rsa'
                elif os.path.exists(os.path.expanduser('~/.ssh/id_dsa')):
                    private_key = '~/.ssh/id_dsa'
                else:
                    raise TypeError, "You have not specified a password or key."

            private_key_file = os.path.expanduser(private_key)
            rsa_key = paramiko.RSAKey.from_private_key_file(private_key_file)
            self._transport.connect(username = username, pkey = rsa_key)

    def _sftp_connect(self):
        """Establish the SFTP connection."""
        if not self._sftp_live:
            self._sftp = paramiko.SFTPClient.from_transport(self._transport)
            self._sftp_live = True

    def get(self, remotepath, localpath = None):
        """Copies a file between the remote host and the local host."""
        if not localpath:
            localpath = os.path.split(remotepath)[1]
        self._sftp_connect()
        self._sftp.get(remotepath, localpath)

    def put(self, localpath, remotepath = None):
        """Copies a file between the local host and the remote host."""
        if not remotepath:
            remotepath = os.path.split(localpath)[1]
        self._sftp_connect()
        self._sftp.put(localpath, remotepath)

    def execute(self, command):
        """Execute the given commands on a remote machine."""
        channel = self._transport.open_session()
        channel.exec_command(command)
        output = channel.makefile('rb', -1).readlines()
        if output:
            return output
        else:
            return channel.makefile_stderr('rb', -1).readlines()

    def close(self):
        """Closes the connection and cleans up."""
        # Close SFTP Connection.
        if self._sftp_live:
            self._sftp.close()
            self._sftp_live = False
        # Close the SSH Transport.
        if self._tranport_live:
            self._transport.close()
            self._tranport_live = False

    def __del__(self):
        """Attempt to clean up if not explicitly closed."""
        self.close()

def main():
    """Little test when called directly."""
    # Set these to your own details.
    myssh = Connection('example.com')
    myssh.put('ssh.py')
    myssh.close()

# start the ball rolling.
if __name__ == "__main__":
    main()

关于python - 如何使用 python 2.3 rsh ssh,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13250899/

相关文章:

python - 如何将名称与列表中的公共(public)元素合并?

python - Django 站点中的搜索功能

python - 调用 pyplot.show() 后保存图形会导致空文件

python - 如何仅合并从 file_a 到 file_b 的唯一行?

Python 2.3 多处理

python - 在嵌入式 Python 中使用 locale.setlocale 而不破坏 C 线程中的文件解析

python - 如何在python脚本中设置环境变量

python 2.3 - 删除目录而不等待进程完成

python - 从 shell 脚本捕获值并在 Python 中使用它,而不使用子进程