How to use paramiko to rename multiple files in Python?
By utilizing the paramiko library, one can establish an SSH connection to a remote server and execute commands to bulk rename files.
Firstly, ensure that the paramiko library has been installed. You can use the following command to install it:
pip install paramiko
Then, you can use the following code to perform bulk operations to change file names.
import paramiko
def rename_files(hostname, username, password, files):
# 创建SSH客户端
client = paramiko.SSHClient()
# 允许连接不在known_hosts文件中的主机
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接远程服务器
client.connect(hostname=hostname, username=username, password=password)
for old_filename, new_filename in files:
# 执行rename命令
command = f'mv {old_filename} {new_filename}'
stdin, stdout, stderr = client.exec_command(command)
# 打印输出结果
print(stdout.read().decode())
# 打印错误信息
print(stderr.read().decode())
# 关闭SSH连接
client.close()
# 定义服务器信息和文件名修改列表
hostname = '服务器地址'
username = '用户名'
password = '密码'
files = [('旧文件名1', '新文件名1'), ('旧文件名2', '新文件名2'), ...]
# 调用函数进行批量文件名修改
rename_files(hostname, username, password, files)
In the code above, the following parts need to be replaced:
- Remote server address: hostname
- Username: The username used to log in to the remote server.
- Password: The password for logging into the remote server.
- A list of file name changes in the format [(‘old file name 1’, ‘new file name 1’), (‘old file name 2’, ‘new file name 2’), …]
The code will sequentially modify file names and output the results and error messages.