通过加j2ssh的方式访问linux服务器

/**
* 通过ssh的方式连接linux服务器
* @return opclient;
* @throws Exception
*/

 public static SftpClient connectSsh(SshClient client,String zzbm){
       SftpClient opclient = null ;
    String user = "root";
    String password = "b3mr~N_ptFDx";
    String IP = "10.111.243.6";
    int pk = 22;
    //获取全局系数配置的linux信息
    String linuxpz = YyzjUtil.getQjxs(20003,zzbm);
    if(StringUtils.isNotEmpty(linuxpz)&&linuxpz.split(";").length==4){
    String pz[] = linuxpz.split(";");
    user =  pz[0];
        password =  pz[1];
        IP =  pz[2];
        pk = Integer.valueOf(pz[3]);
    }
       //设置用户名和密码
       PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();
       pwd.setUsername(user);
       pwd.setPassword(password);
     try{  
    // 设置第一次登陆的时候提示,可选值:(ask | yes | no)
       ConsoleKnownHostsKeyVerification console = new ConsoleKnownHostsKeyVerification();
       client.connect(IP,pk,console);
       int result=client.authenticate(pwd);
       if(result==AuthenticationProtocolState.COMPLETE){//如果连接完成
           System.out.println("==============="+result+"=============");
           opclient = client.openSftpClient();
       }
      
   }catch(IOException e){
       e.printStackTrace();
   }
        return opclient;

}

/**
* ssh生成服务器上文件夹并设置权限

* @param gddwbm
* @param wjmc
* @throws Exception
*/
public void makefilePath(String path) throws Exception {
//查询外派的FTP路径
String filepath = path;
try{
opclient.cd(filepath);
opclient.chmod(0777, filepath);//设置文件夹权限w,r,x
           }catch(FileNotFoundException sException){
   opclient.mkdir(filepath);
   opclient.cd(filepath);
   opclient.chmod(0777, filepath);
    }

}

 /*
 * sftp通过递归得到某一路径下所有的目录及其文件
  */
public  void getsSfiles(String filePath) {
try{
 @SuppressWarnings("unchecked")
List<SftpFile> list = opclient.ls(filePath);
 ArrayList<String> wjm =new ArrayList<String>();
        for (SftpFile f : list) {
           //System.out.println(f.getFilename());
           if(true==f.isFile()){ 
           String wjlj = f.getAbsolutePath().substring(0, f.getAbsolutePath().lastIndexOf("/")+1);
           wjm.add(f.getFilename().substring(0, f.getFilename().lastIndexOf(".")));
           map.put(wjlj, wjm); 
           //回存文件列表
           filelist.add(f.getAbsolutePath());
           }
     
    if(f.isDirectory()&&!".".equals(f.getFilename())&&!"..".equals(f.getFilename())){
      /*
 * 递归调用
 */
     getsSfiles(f.getAbsolutePath());
    
//System.out.println("显示"+f.getAbsolutePath().substring(0, f.getAbsolutePath().lastIndexOf("/")+1)+"下所有子目录及其文件"+f.getFilename());
    }
   }
    } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
   }

----------------------------------ConsoleKnownHostsKeyVerification ——————————————

package com.csg.util.yyzj;
/**
 * 通过Ssh协议连接到服务器执行执行的指令
用j2ssh-core-0.2.9.jar连接远程主机时,第一次会需要用户输入Yes\No\Always来是否接受主机公匙,
如果程序在后台运行,无法与用户交互,所以需要ConsoleKnownHostsKeyVerification类,
然后在连接时使用SshClient.connect(String hostname, int port,HostKeyVerification hosts),hosts参数使用此类的对象。
 
下面是ConsoleKnownHostsKeyVerification类的代码
 */




import java.io.File;
import java.io.IOException;


import com.sshtools.j2ssh.transport.AbstractKnownHostsKeyVerification;
import com.sshtools.j2ssh.transport.InvalidHostFileException;
import com.sshtools.j2ssh.transport.publickey.SshPublicKey;




public class ConsoleKnownHostsKeyVerification extends
        AbstractKnownHostsKeyVerification {

    public ConsoleKnownHostsKeyVerification() throws InvalidHostFileException {
        super(new File(System.getProperty("user.home"), ".ssh" + File.separator + "known_hosts").getAbsolutePath());
    }
    public ConsoleKnownHostsKeyVerification(String knownhosts)
            throws InvalidHostFileException {
        super(knownhosts);
    }
    public void onHostKeyMismatch(String host, SshPublicKey pk,
            SshPublicKey actual) {
        try {
            System.out.println("The host key supplied by " + host + " is: " + actual.getFingerprint());
            System.out.println("The current allowed key for " + host + " is: "  + pk.getFingerprint());
            getResponse(host, pk);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void onUnknownHost(String host, SshPublicKey pk) {
        try {
            System.out.println("The host " + host  + " is currently unknown to the system");
            System.out.println("The host key fingerprint is: " + pk.getFingerprint());
            getResponse(host, pk);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取用户输入的信息,判断是否接受主机公匙
     * <p>
     * 修改:xxx ,去掉从流中获取信息,直接接受公匙,注释掉的代码为源码
     * 
     * @param host
     *            主机ip
     * @param pk
     *            主机公匙
     * @throws InvalidHostFileException
     * @throws IOException
     */
    private void getResponse(String host, SshPublicKey pk)
            throws InvalidHostFileException, IOException {
        if (isHostFileWriteable()) {
            allowHost(host, pk, true);
        }
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值