【发布时间】:2019-10-22 17:10:03
【问题描述】:
我正在尝试通过 WIFI 将文件从 android 应用程序发送到 RaspberryPi。
我可以连接到 RPI 并通过 SSH 向它发送命令。
这是我用来发送 ssh 命令的函数:
public static String executeRemoteCommand(final String username, final String password, final String hostname, final int port, final File file)
throws Exception {
JSch jsch = new JSch();
Session session = jsch.getSession(username, hostname, port);
session.setPassword(password);
// Avoid asking for key confirmation
Properties prop = new Properties();
prop.put("StrictHostKeyChecking", "no");
session.setConfig(prop);
session.connect();
// SSH Channel
ChannelExec channelssh = (ChannelExec)
session.openChannel("exec");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
channelssh.setOutputStream(baos);
// Execute command
channelssh.setCommand("scp " + file + " " + username + "@" + hostname + ":/home/pi/Desktop");
channelssh.connect();
try{Thread.sleep(5000);}catch(Exception ee){}
channelssh.disconnect();
return baos.toString();
}
这是要发送的 SSH 命令
scp /storage/emulated/0/Download/201906071017.txt pi@192.168.4.1:/home/pi/Desktop
我尝试在 windows 终端上运行 SSH 命令并成功上传文件
编辑:
我在.connect() 和.disconnect() 之间添加了这段代码,等待我收到命令的响应以断开与 RPi 的连接
channelssh.setErrStream(System.err);
InputStream in=channelssh.getInputStream();
channelssh.connect();
byte[] tmp=new byte[1024];
while(true){
while(in.available()>0){
int i=in.read(tmp, 0, 1024);
if(i<0)break;
System.out.print(new String(tmp, 0, i));
}
if(channelssh.isClosed()){
if(in.available()>0) continue;
System.out.println("exit-status: "+channelssh.getExitStatus());
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
channelssh.disconnect();
现在我在日志中获得权限被拒绝,用户名和密码正确。
W/System.err: Permission denied, please try again.
W/System.err: Permission denied, please try again.
W/System.err: Permission denied (publickey,password).
W/System.err: lost connection
I/System.out: exit-status: 1
【问题讨论】:
-
那么你的问题到底是什么?
-
我没有收到任何错误消息,但文件没有出现在 RPI 上
-
我会删除我的答案,它不能解决你的问题。你肯定需要在连接和断开之间做点什么。您可能需要将文件写入输出流,但您可能需要更改 scp 命令。
标签: java android ssh raspberry-pi file-transfer