您好,登錄后才能下訂單哦!
本篇內容介紹了“go ssh怎么連接遠程服務器并執行命令”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
下面的代碼展現了公鑰在可執行文件同目錄或者直接以字符串形式定義在文件中兩種形式
log.Fatal觸發后會引發程序退出 打印輸出內容 退出應用程序 defer函數不會執行
package main import ( "fmt" "log" "os" "time" "github.com/mitchellh/go-homedir" "golang.org/x/crypto/ssh" ) var serverKey string = `-----BEGIN RSA PRIVATE KEY----- LIIEowIBAAKCAQEAqq+P9RB3l6qFTNKwh+cgR3jbBQWt1oFZ+4BoutKxEtHM/bOK ADiSoHVr4+7L8Q+I9GgVyW1GR/H8UzhW5TAUvNwIklyX7zmqdZ8MXoTsZhenmolQ z9gMhXC3TLKXtnu6666666666666666666lcZk6DHdZXE+BBRYDkVbaaMpq+5 xEmbwJQZqX1L9YLM6666666666666666666JHJQ+g3t5qCZ85eVFpt3gEt/IiY2X PVvPBUaS5xn1N8KDlp121+vBVzuqYBa7TOqK6xz9V2/86yj4kD+mldgXrQBAvn3g C6cMiLqt9XPMjZF+3ML6666666666666666666wIDAQABAoIBAQCJj2iD5zubHjDE U2E2hk17jKlniMYrhKBSk56666666666666666666bUQAtSnkI9MKtwAoEEt+HEZx g4x0taVg+CxoWPuSL666666666666666666666rgDsbVrcFRMCNVkuR/JQXnZB E4b0+5eFL4FLe16FI6lVC0GqPRdKAIkXloMpVsJ/ptNMx8QI8C6zSy68NRzV7oJJ VsBbr4W1Ptez28zBzmfj66666666666666666669jWKM11EzvjpWHPNnAi LWQX9NQcSmMGTmw46666666666666666666sCgt8Vva474lVgEWyVsB6FBUOOz KzF13CuhAoGBANyuLwalH6666666666666666666wjGveIcrwM/opza+g3YprO+uoKIj 5O+lVbPOtXQGKxE/gagPMWHIdqbjZYWQ+Sq17GjJeU6kP9Rzwg04G5xi3FNG6/2f 1g7tyMiyrZdcdUIcnx5+6666666666666666666eqPuwDJotBasjkAcyPfAoGBAMYA +hb/Dyrj3PSOBiznqAc66666666666666666660WgtVkc+ZOdDR7PL2VZU sLltu3GjXm6am5aeu66666666666666666664i0Uj8cQI19bLSDqiSLXus5zn X7/QP6777777777777777LFahJd8WqVdTnSb7nZAoGAcXymNG2fKH4Amo5SXWty zvrTy0do3WKz0nfb3jxV6666666666666666666+8vcRA97txixFY9I7YRNxkWK zdsmy7Co0LeJF9G7/p5XHLJ+idkULacQJzdDpWq1+PwUVT5w2fbIGUrQmjBwzuPv niZP6P+ndL09HJc3xja6666666666666666666D3ARBgr4JoU5JqbNxHtfZaEV t/0A9b+aw0aXNmU4t70ARHtDDHwFAZBqsT+UNGjgN2XIuabXlT7JBgzkt/Gh6ff6 EzGx1C86Z80+sEU/wJ+nrjNfwdicRmJwMonPbdzd7vhzUymeDsPSBKVldH8rjwQ3 uHMwmQKBgAYAD+6666666666666666666Zy+eopHoOk5I//U8Rj3YbvX/Nu/748 oNwAaRaaSOjTJAdqfzAQHmJGVAJVjK7zkWyFPnbVPRT46cXV4j7LvbJivQ55eXdf 8VhofmV+sItXTmnB66666666666666666667t1nBoEtStJ6/ -----END RSA PRIVATE KEY-----` // ssh配置類型 type sshConfig struct { sshHost string sshUser string sshPasswrod string sshType string // password或者key sshKeyPath string // ssh id_rsa.id路徑 sshPort int } // 公鑰在代碼中是string func publicKeyStrAuth(key string) ssh.AuthMethod { keyStr, err := homedir.Expand(key) if err != nil { log.Fatal("find key's home dir failed", err) } var keyByte []byte = []byte(keyStr) signer, err := ssh.ParsePrivateKey(keyByte) if err != nil { log.Fatal("ssh key signer failed", err) } return ssh.PublicKeys(signer) } // 公鑰在文件中 func publicKeyFileAuth(keyPath string) ssh.AuthMethod { keyExpandPath, err := homedir.Expand(keyPath) if err != nil { log.Fatal("find key's home dir failed", err) } key, err := os.ReadFile(keyExpandPath) if err != nil { log.Fatal("ssh key file read failed", err) } signer, err := ssh.ParsePrivateKey(key) if err != nil { log.Fatal("ssh key signer failed", err) } return ssh.PublicKeys(signer) } func sshRemoteExcute(sshCfg sshConfig, cmd string) { // 創建ssh登錄配置 config := &ssh.ClientConfig{ Timeout: time.Second, // ssh連接time out時間一秒鐘,如果ssh驗證錯誤會在一秒鐘返回 User: sshCfg.sshUser, HostKeyCallback: ssh.InsecureIgnoreHostKey(), // 這個可以,但是不夠安全 } if sshCfg.sshType == "password" { config.Auth = []ssh.AuthMethod{ssh.Password(sshCfg.sshPasswrod)} } else { // config.Auth = []ssh.AuthMethod{publicKeyFileAuth(sshCfg.sshKeyPath)} config.Auth = []ssh.AuthMethod{publicKeyStrAuth(sshCfg.sshKeyPath)} // return } // dial 獲取ssh client addr := fmt.Sprintf("%s:%d", sshCfg.sshHost, sshCfg.sshPort) sshClient, err := ssh.Dial("tcp", addr, config) if err != nil { log.Fatal("genarate ssh client fail", err) } defer sshClient.Close() // 創建ssh-session session, err := sshClient.NewSession() if err != nil { log.Fatal("genarate ssh client fail", err) } defer session.Close() // 執行遠程命令 combo, err := session.CombinedOutput(cmd) if err != nil { log.Fatal("remote excute cmd fail", err) } log.Println("cmd output:", string(combo)) log.Println("@@@Excute remote cmd successfully ~~") } func main() { var svnConfig sshConfig svnConfig.sshHost = "192.168.xx.xxx" svnConfig.sshUser = "root" svnConfig.sshPasswrod = "" svnConfig.sshType = "key" // password或者key svnConfig.sshKeyPath = "./key在同目錄下" // ssh id_rsa.id路徑 svnConfig.sshKeyPath = serverKey svnConfig.sshPort = 22 var newSvnName string fmt.Println("請輸入新用戶用戶名:") fmt.Scanln(&newSvnName) testCmd := "whoami" sshRemoteExcute(svnConfig, testCmd) }
import paramiko def ssh_private_key(rsa_file, hostname, port, username, cmd): '''私鑰ssh連接cetnos方法 ''' ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) private_key = paramiko.RSAKey.from_private_key_file( rsa_file) # 指定私鑰所在文件 # 連接服務器 ssh.connect( hostname=hostname, port=port, username=username, pkey=private_key, timeout=5 ) stdin, stdout, stderr = ssh.exec_command(cmd) result = stdout.read().decode('utf-8') ssh.close() return result def ssh_pwd(hostname, port, username, pwd, cmd): '''賬號密碼連接centos方法 ''' ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect( hostname=hostname, port=port, username=username, password=pwd, timeout=10 ) stdin, stdout, stderr = ssh.exec_command(cmd, get_pty=True) result = stdout.read().decode('utf-8') ssh.close() return result def ssh_transfer_file(local_file, remote_file): '''上傳文件到服務器 ''' transport = paramiko.Transport('192.168.xxx.xxx', 22) transport.connect(username='root', password='1234') sftp = paramiko.SFTPClient.from_transport(transport) sftp.put(local_file, remote_file) # 從本地上傳文件到遠程主機 transport.close() if __name__ == "__main__": # SVN創建用戶 res = ssh_pwd(hostname='192.168.xxx.xx', port=22, username='root', pwd='', cmd='/home/svn/useradd.sh xxx') print(res)
“go ssh怎么連接遠程服務器并執行命令”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。