从SoapUI中的groovy脚本我需要连接到mysql数据库来执行一些查询。问题是由于安全原因,无法进行外部访问。 因此,需要获取ssh访问(如隧道)并在本地调用mysql。
最初我正在阅读以下项目属性,然后连接到mysql:
ServerUrl=jdbc:mysql://10.255.255.122:3306/db
ServerDbUser=user
ServerDbPwd=password
ServerDriver=com.mysql.jdbc.Driver
def url=testRunner.testCase.testSuite.project.getPropertyValue("ServerUrl")
def usr=testRunner.testCase.testSuite.project.getPropertyValue("ServerDbUser")
def pwd=testRunner.testCase.testSuite.project.getPropertyValue("ServerDbPwd")
def driver=testRunner.testCase.testSuite.project.getPropertyValue("ServerDriver")
com.eviware.soapui.support.GroovyUtils.registerJdbcDriver(driver)
sqlServer = Sql.newInstance(url, usr, pwd, driver)`
但是这没有用,所以现在需要首先使用IP 10.255.255.122建立与服务器的ssh连接,然后在本地打开mysql连接。所以我猜服务器URL将改为:
ServerUrl=jdbc:mysql://127.0.0.1:3306/db
但我不知道如何首先设置与服务器的ssh连接。
有人可以帮我这个吗?
感谢。
答案 0 :(得分:0)
查看http://forum.soapui.org/viewtopic.php?t=15400和connect to remote mysql database through ssh using java
它将为您提供在soapUI中实现它的想法。
下面是Ripon Al Wasim的代码,可以在上面提到的stackoverflow链接中找到答案
package mypackage;
import java.sql.*;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class UpdateMySqlDatabase {
static int lport;
static String rhost;
static int rport;
public static void go(){
String user = "ripon";
String password = "wasim";
String host = "myhost.ripon.wasim";
int port=22;
try
{
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
lport = 4321;
rhost = "localhost";
rport = 3306;
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
session.connect();
int assinged_port=session.setPortForwardingL(lport, rhost, rport);
System.out.println("localhost:"+assinged_port+" -> "+rhost+":"+rport);
}
catch(Exception e){System.err.print(e);}
}
public static void main(String[] args) {
try{
go();
} catch(Exception ex){
ex.printStackTrace();
}
System.out.println("An example for updating a Row from Mysql Database!");
Connection con = null;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://" + rhost +":" + lport + "/";
String db = "testDB";
String dbUser = "wasim";
String dbPasswd = "riponalwasim123";
try{
Class.forName(driver);
con = DriverManager.getConnection(url+db, dbUser, dbPasswd);
try{
Statement st = con.createStatement();
String sql = "UPDATE MyTableName " +
"SET email = 'ripon.wasim@smile.com' WHERE email='peace@happy.com'";
int update = st.executeUpdate(sql);
if(update >= 1){
System.out.println("Row is updated.");
}
else{
System.out.println("Row is not updated.");
}
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}