golang ssh 登录到linux 服务器修改文件名
在Go语言中,可以使用golang.org/x/crypto/ssh包来进行SSH登录和执行命令。下面是一个使用Go语言SSH登录到Linux服务器并修改文件名的示例代码:
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"golang.org/x/crypto/ssh"
)
func main() {
// SSH连接配置
config := &ssh.ClientConfig{
User: "your-username",
Auth: []ssh.AuthMethod{
ssh.Password("your-password"),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
// SSH连接
client, err := ssh.Dial("tcp", "your-server-ip:22", config)
if err != nil {
log.Fatalf("Failed to dial: %s", err)
}
defer client.Close()
// 执行命令
session, err := client.NewSession()
if err != nil {
log.Fatalf("Failed to create session: %s", err)
}
defer session.Close()
// 修改文件名
err = session.Run("mv old-file-name new-file-name")
if err != nil {
log.Fatalf("Failed to run command: %s", err)
}
// 检查文件是否重命名成功
_, err = session.Output("ls new-file-name")
if err != nil {
log.Fatalf("Failed to rename file: %s", err)
}
fmt.Println("File renamed successfully")
}
请注意,你需要将your-username、your-password和your-server-ip替换为你实际的用户名、密码和服务器IP地址。同时,你还需要确保你的计算机中安装了golang.org/x/crypto/ssh包
AI 优化版
原文地址:https://www.cveoy.top/t/topic/i1rt 著作权归作者所有。请勿转载和采集!