javajsch切换⽤户_java–JSch:有没有办法将⽤户环境变量
暴...
我正在尝试运⾏使⽤本地Linux逻辑路径的命令,如cat $test_dir / test.dat,但逻辑路径$test_dir(⽤户环境变量)不能通过ChannelExec获得.但是当我使⽤交互式ChannelShell时,我能够看到⽤户变量和命令在交互式会话中运⾏良好.我只能从“exec”会话中查看系统级环境变量.甚⾄可以使⽤JSch库,如果是,那么我该如何实现它,如果不是我将使⽤什么库来实现这⼀⽬标?
在下⾯添加我的类代码:
`public class SecureShell {
private static final Logger logger = Logger(SecureShell.class);
private String uName;
private String pWord;
private String hName;
private int port;
private Session session = null;
private Channel channel = null;
/**Create an instance to start and stop the remote shell and execute commands remotely via java.
*
* @param uName
* host username
* @param pWord
* host password
* @param hName
* host name
* @param port
* host port number
*/
public SecureShell(String uName, String pWord, String hName, int port) {
this.uName = uName;
this.pWord = pWord;
this.hName = hName;
this.port = port;
}
/**Create an instance to start and stop the remote shell and execute commands remotely via java.
*
*@param uName
* host username
* @param pWord
* host password
* @param hName
* host name
*/
public SecureShell(String uName, String pWord, String hName) { this.uName = uName;
this.pWord = pWord;
this.hName = hName;
this.port = 22;
}
/**Start the session with the host.
* @return
* true if the session started successfully, false otherwise
*/
public boolean startSession() {
JSch jsch = new JSch();
try {
session = Session(uName, hName, port);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword(pWord);
} catch (JSchException jsche) {
<(Message());
return false;
}
return true;
}
/** Execute commands on the host;
* @param command
java环境变量自动配置* command to be executed on the host.
* @return
* status of the execution
*/
public int execute(String command) {
int status = -1;
if(session != null && session.isConnected()) {
try {
channel = session.openChannel("exec");
//((ChannelExec)channel).setEnv("LC_XXX", "xxxxxxx"); ((ChannelExec)channel).setPty(true); ((ChannelExec) channel).setCommand(command); InputStream in = InputStream();
byte[] buffer = new byte[1024];
while(true){
while(in.available()>0){
int ad(buffer, 0, 1024);
System.out.print(new String(buffer, 0, i));
if(i<0)
break;
}
if(channel.isClosed()){
if(in.available()>0)
continue;
status = ExitStatus();
break;
}
}
} catch (JSchException jsche) {
<(Message());
} catch (IOException ioe) {
<(Message());
} finally {
if(channel!=null && channel.isConnected())
channel.disconnect();
}
}
return status;
}
/**Stop the session with the remote.
*
*/
public void stopSession() {
if(session!=null && session.isConnected())
session.disconnect();
}
public static void main(String[] args) {
SecureShell ssh = new SecureShell("user", "password", "hostname"); ssh.startSession();
System.out.ute("env"));
ssh.stopSession();
}
}`
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论