JAVA\Python\C#\C++實現SSH2遠程調用Linux主機執行命令

JAVAjava

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class SSHHelper {
    /**
     * 遠程 執行命令並返回結果調用過程 是同步的(執行完纔會返回)
     * @param host  linux主機名
     * @param user  用戶名
     * @param psw   密碼
     * @param port  端口
     * @param command   命令行
     * @return
     */
    public static String exec(String host,String user,String psw,int port,String command){
        StringBuffer sb= new StringBuffer();
        Session session =null;
        ChannelExec openChannel =null;
        try {
            JSch jsch=new JSch();
            session = jsch.getSession(user, host, port);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");//跳過公鑰的詢問
            session.setConfig(config);
            session.setPassword(psw);
            session.connect(5000);//設置鏈接的超時時間
            openChannel = (ChannelExec) session.openChannel("exec");
            openChannel.setCommand(command); //執行命令
            int exitStatus = openChannel.getExitStatus(); //退出狀態爲-1,直到通道關閉
            System.out.println(exitStatus);

            // 下面是獲得輸出的內容
            openChannel.connect();
            InputStream in = openChannel.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String buf = null;
            while ((buf = reader.readLine()) != null) {
                sb.append(buf+"\n");
            }
        } catch (JSchException | IOException e) {
            sb.append(e.getMessage()+"\n");
        }finally{
            if(openChannel!=null&&!openChannel.isClosed()){
                openChannel.disconnect();
            }
            if(session!=null&&session.isConnected()){
                session.disconnect();
            }
        }
        return sb.toString();
    }


    public static void main(String args[]){
        String exec = exec("***.***.***.***", "***", "***", 22, "ls");
        System.out.println(exec);
    }
}

Pythonpython

import paramiko

ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.connect(hostname='***.***.***.***', port=22,username='root', password='password')
stdin, stdout, stderr = ssh.exec_command("ls -lh")
print(stdout.read().decode('UTF-8', 'ignore'))
ssh.close()

C#linux

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Tamir.SharpSsh;

namespace SSHTest{
class Program
{

public static string ssh_conn(string ip, string root, string pass, string command)
        {

            SshStream ssh = new SshStream(ip, root, pass);
            ssh.Prompt = "#";
            ssh.RemoveTerminalEmulationCharacters = true; 
            string response = ssh.ReadResponse();
            ssh.Write(command);
            ssh.Flush();
            ssh.Write("/n");
            response = ssh.ReadResponse();
            //Console.WriteLine(response);
            return response;

        }
}

}

C++ios

#include <iostream>
#include "ssh2.h"
 
int main(int argc, const char * argv[])
{
    using namespace std;
    using namespace fish;
    
    Ssh2 ssh("***.***.***.***");
    ssh.Connect("test","xxxxxx");
    Channel* channel = ssh.CreateChannel();
    channel->Write("cd /;pwd");
    cout<<channel->Read()<<endl;
    channel->Write("ssh 127.0.0.1");
    cout<<channel->Read(":")<<endl;
    channel->Write("xxxxxx");
    cout<<channel->Read()<<endl;
    channel->Write("pwd");
    cout<<channel->Read()<<endl;
    delete channel;
    return 0;
}
相關文章
相關標籤/搜索