java ssh jsch,使用JSch通过Java通过ssh将命令发送到远程服务器

I'm trying to set up a class so that I can ssh into a remote server (I have the IP, username, and password) and then send a command like "echo "test"" and then receive back the output (e.g., "test"). I'm using JSch to do this but I don't understand how to do it.

import com.jcraft.jsch.*;

public class ConnectSSH {

public int execute (String command) {

JSch jsch = new JSch();

String ip = "00.00.00.00;

String user = "root";

String pass = "password";

int port = 22;

try {

Session session = jsch.getSession(user, ip, port);

session.setPassword(pass);

session.connect();

...

I'm not sure what to do, I'm stuck after connecting.

Any advice is greatly appreciated.

解决方案

Try this:

JSch jsch=new JSch();

Session session=jsch.getSession(remoteHostUserName, RemoteHostName, 22);

session.setPassword(remoteHostpassword);

Properties config = new Properties();

config.put("StrictHostKeyChecking", "no");

session.setConfig(config);

session.connect();

ChannelExec channel=(ChannelExec) session.openChannel("exec");

BufferedReader in=new BufferedReader(new InputStreamReader(channel.getInputStream()));

channel.setCommand("pwd;");

channel.connect();

String msg=null;

while((msg=in.readLine())!=null){

System.out.println(msg);

}

channel.disconnect();

session.disconnect();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java使用jsch库进行远程文件下载可以实现通过SSH协议从远程服务器下载文件。下面是一个简单的示例代码: ```java import com.jcraft.jsch.*; public class RemoteFileDownloader { public static void main(String[] args) { String host = "远程服务器IP"; String username = "用户名"; String password = "密码"; String remoteFilePath = "远程文件路径"; String localFilePath = "本地保存路径"; JSch jsch = new JSch(); Session session = null; try { session = jsch.getSession(username, host, 22); session.setConfig("StrictHostKeyChecking", "no"); session.setPassword(password); session.connect(); ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp"); channelSftp.connect(); channelSftp.get(remoteFilePath, localFilePath); channelSftp.disconnect(); } catch (JSchException | SftpException e) { e.printStackTrace(); } finally { if (session != null) { session.disconnect(); } } } } ``` 请将代码中的以下变量替换为实际的值: - `host`: 远程服务器的IP地址或域名 - `username`: 远程服务器的用户名 - `password`: 远程服务器的密码 - `remoteFilePath`: 要下载的文件在远程服务器上的路径 - `localFilePath`: 下载后保存到本地的路径 这段代码使用jsch库创建一个SSH会话并连接到远程服务器。然后,通过打开SFTP通道并调用`get()`方法来下载文件。最后,关闭SFTP通道和SSH会话。 请注意,为了运行这段代码,你需要将jsch库添加到你的项目中。你可以从jsch官方网站[https://www.jcraft.com/jsch/](https://www.jcraft.com/jsch/)下载该库的jar文件,并将其添加到你的项目的类路径中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值