How to connect into Secured Database connection that need ssh

“Does anyone have experience connecting to a secure database that requires an SSH connection to a specific server? If so, is it possible to connect to secured database server connection using database libraries like SQLx?”

I tried Google but couldn't find any relevant results, Would appreciate some example/guidance/pointers. Thanks

That's not how databases usually work. They can use SSL but not SSH, which is a shell protocol. What specific kind of database are you trying to use?

You can create a SSH tunnel, and access as it were a local database.

My goal is to automate some tasks using Rust, which requires SSH tunnel integration in my code. I adhere to the existing rules for using DBeaver, which is the standard configuration at my workplace.

The database that i want to to use is mysql.

First, you'd need to find out whether "SSH tunnel" is a DBeaver concept or a MySQL concept.

I think that creating an SSH tunnel and connecting to a database are orthogonal tasks and you can solve these independently.

1/ First, find how to create a SSH tunnel using openssh commands (for example; there are tutorials about this on the internet depending on what your OS is).

2/ Second, use a rust library that can talk to MySql just as you would use it for a local connection, but instead point it to the port that you just created a SSH tunnel to (the "entry" of the tunnel, if you will).

Finally, if you need everything to be in rust, you can think about how to move point 1/ from a bash script to calling openssh from your rust program.

1 Like

Thank you all for your input, The solution that I have in mind for this is:

  1. Using a thread to create a tunneling (because this will block the process),
  2. Creating another thread to perform database operations.
  3. When the database operations are done, the tunneling thread is closed by the main process.

I hope this solution makes sense. I`m still new to Rust, if you have any other suggestions, please feel free to share them.

After exploring several solutions, this works for me.I hope it will be helpful for anyone who needs it.

println!("Port Forward enabled");
    let tcp: TcpStream = TcpStream::connect(&conn_str.local_ip).unwrap();
    let mut sess: Session = Session::new().unwrap();
    sess.set_tcp_stream(tcp);
    sess.handshake().unwrap();
    sess.userauth_password(&conn_str.username, &conn_str.password)
        .unwrap();
    let mut channel: ssh2::Channel = sess.channel_session().unwrap();
    channel.exec(&conn_str.tunnel_conn).unwrap(); // "ssh -i file.pem -L 9999:127.0.0.1:9999 user01@11.11.11.11"
todo!();
channel.wait_close().ok();
    println!("Port Forward Disabled {}", channel.exit_status().unwrap());
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.