python paramiko sftp_Python paramiko.sftp_client方法代码示例

# 需要导入模块: import paramiko [as 别名]

# 或者: from paramiko import sftp_client [as 别名]

def file(

self,

remote_path,

content,

use_sudo=False,

owner=None,

permissions=None,

username=None,

silent=False

):

""" Method to create a remote file with the specified `content`

:param remote_path: destination folder in which to copy the local file

:param content: content of the file

:param use_sudo: allow to copy file in location with restricted permissions

:param owner: user that will own the file on the remote host

:param permissions: permissions to apply on the remote file (chmod format)

:param username: sudo user

:param silent: disable logging

Usage::

# create file on remote host and with specified content at the specified path

>>> ssh_session.file(remote_path='/path/to/remote/file', content='file content')

# create file on remote host and with specified content at the specified path needing sudo permissions

>>> ssh_session.file(remote_path='/path/to/remote/file', content='file content', use_sudo=True)

# create file on remote host and with specified content at the specified path

# with specified owner and permissions

>>> ssh_session.file(remote_path='/path/to/remote/file', content='file content',

... owner='other_user', permissions='700')

"""

if not silent:

logger.debug("Create file '%s' on remote host '%s' as '%s'" % (remote_path, self.host, self.username))

sftp_client = self.get_sftp_client()

copy_path = remote_path

if use_sudo:

# copy local file on remote host in temporary dir

copy_path = "/tmp/%s" % util.id_generator(size=15)

# create file remotely

with sftp_client.file(copy_path, mode='w+') as remote_file:

remote_file.write(content)

# mv this file in the final destination

if use_sudo:

move_command = "mv %s %s" % (copy_path, remote_path)

self.run_cmd(move_command, silent=True, username=username or 'root')

# file will be owned by the specified user

if owner:

full_owner = owner

if ':' not in owner:

full_owner = '{0}:{0}'.format(owner)

self.run_cmd("sudo chown %s %s" % (full_owner, remote_path), silent=True)

if permissions:

self.run_cmd("sudo chmod %s %s" % (permissions, remote_path), silent=True)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值