Para poder trabajar con SSH lo primero que necesitamos es tener un servidor al cual podamos acceder mediante este protocolo. Si no sabes como hacer esto, en un post anterior expliqué cómo acceder a un servidor Synology NAS por SSH.
Para poder hacer las conexiones por SSH se han utilizado dos librerías:
Las dos básicamente tienen las mismas funcionalidades, exceptuando que Rebex confirma que tiene compatibilidad con Xamarin y dispone de métodos asíncronos en todos sus comandos.
Antes de poner todo el código de la aplicación voy a mostraros cómo sería la versión final de la App:
Para realizarlo todo de una manera mas cómoda he escrito todo en la misma clase. Lo mas recomendable es hacer una clase diferente con aquellas funciones que se van a repetir. A continuación muestro el código de la aplicación:
Diseño
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="8dp" android:layout_gravity="center_horizontal" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:showIn="@layout/activity_main"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <android.support.design.widget.TextInputLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="0dp" android:layout_weight="70" android:layout_height="wrap_content"> <EditText android:id="@+id/hostname" android:layout_width="match_parent" android:layout_height="wrap_content" android:singleLine="true" android:inputType="text" android:textColor="@android:color/black" android:hint="Hostname"/> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="0dp" android:layout_weight="30" android:layout_height="wrap_content"> <EditText android:id="@+id/port" android:layout_width="match_parent" android:layout_height="wrap_content" android:singleLine="true" android:inputType="number" android:maxLength="5" android:textColor="@android:color/black" android:hint="Port"/> </android.support.design.widget.TextInputLayout> </LinearLayout> <android.support.design.widget.TextInputLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp"> <EditText android:id="@+id/user" android:layout_width="fill_parent" android:layout_height="wrap_content" android:singleLine="true" android:inputType="text" android:textColor="@android:color/black" android:hint="User"/> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" app:passwordToggleEnabled="true"> <EditText android:id="@+id/password" android:layout_width="fill_parent" android:layout_height="wrap_content" android:singleLine="true" android:inputType="textPassword" android:textColor="@android:color/black" android:hint="Password"/> </android.support.design.widget.TextInputLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/btnConnect" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="40" android:layout_marginTop="16dp" android:text="Conectar" android:textAllCaps="false"/> <Button android:id="@+id/btnDisconnect" android:layout_width="0dp" android:layout_weight="40" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:enabled="false" android:text="Desconectar" android:textAllCaps="false"/> <Button android:id="@+id/btnBack" android:layout_width="0dp" android:layout_weight="20" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:enabled="false" android:text="Volver" android:textAllCaps="false"/> </LinearLayout> <ListView android:id="@+id/listView" android:layout_marginTop="8dp" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout> |
Código
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 |
using System; using System.Collections.Generic; using Acr.UserDialogs; using Android.App; using Android.OS; using Android.Support.V7.App; using Android.Views; using Android.Widget; using Rebex.Net; using Rebex.TerminalEmulation; using Renci.SshNet; using SSH.Operations; namespace SSH { [Activity(Label = "@string/app_name", Theme = "@style/AppTheme.NoActionBar", MainLauncher = true)] public class MainActivity : AppCompatActivity { EditText hostName, user, password, port; Button btnConnect, btnDisconnect, btnBack; SshClient client; Spinner spinner; Ssh ssh; ListView list; String path; String spinnerSelected; Scripting scripting; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.activity_main); UserDialogs.Init(this); Rebex.Licensing.Key = Constants.RebexKey; Android.Support.V7.Widget.Toolbar toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar); SetSupportActionBar(toolbar); Instancias(); Acciones(); } private void Instancias() { hostName = FindViewById<EditText>(Resource.Id.hostname); user = FindViewById<EditText>(Resource.Id.user); port = FindViewById<EditText>(Resource.Id.port); password = FindViewById<EditText>(Resource.Id.password); btnConnect = FindViewById<Button>(Resource.Id.btnConnect); btnDisconnect = FindViewById<Button>(Resource.Id.btnDisconnect); btnBack = FindViewById<Button>(Resource.Id.btnBack); list = FindViewById<ListView>(Resource.Id.listView); spinner = FindViewById<Spinner>(Resource.Id.spinner); } private void Acciones() { btnConnect.Click += OnConnectSSH; btnDisconnect.Click += OnDisconnectSSH; btnBack.Click += OnBackClick; list.ItemClick += OnListClicked; spinner.ItemSelected += OnSpinnerCLick; } //Pulsacion del spinner para cambiar de libreria SSH private void OnSpinnerCLick(object sender, AdapterView.ItemSelectedEventArgs e) { spinnerSelected = spinner.GetItemAtPosition(e.Position).ToString(); } // Boton para volver atras private void OnBackClick(object sender, EventArgs e) { if (spinnerSelected.Equals(GetString(Resource.String.rebexssh))) BackDirectoryRebex(); else if (spinnerSelected.Equals(GetString(Resource.String.sshnet))) BackDirectorySSH(); } // Seleccion de la lista de directorios o ficheros private void OnListClicked(object sender, AdapterView.ItemClickEventArgs e) { String selected = list.GetItemAtPosition(e.Position).ToString(); if (selected.Contains(".")) { Toast.MakeText(this, "No se puede abrir el archivo", ToastLength.Short).Show(); return; } string directory = FormatedPath(selected); if (spinnerSelected.Equals(GetString(Resource.String.rebexssh))) ChangeDirectoryRebex(directory); else if (spinnerSelected.Equals(GetString(Resource.String.sshnet))) ChangeDirectorySSH(directory); } // Desconectar cliente dependiendo de la librería private void OnDisconnectSSH(object sender, EventArgs e) { try { if (spinnerSelected.Equals(GetString(Resource.String.rebexssh))) { ssh.Disconnect(); if (!ssh.IsConnected) { DisconnectSSH(); Toast.MakeText(this, "Cliente desconectado", ToastLength.Short).Show(); } } else if (spinnerSelected.Equals(GetString(Resource.String.sshnet))) { client.Disconnect(); if (!client.IsConnected) { DisconnectSSH(); Toast.MakeText(this, "Cliente desconectado", ToastLength.Short).Show(); } } } catch (Exception ex) { Toast.MakeText(this, ex.Message, ToastLength.Long).Show(); } } private void DisconnectSSH() { list.Adapter = null; btnDisconnect.Enabled = false; btnBack.Enabled = false; btnConnect.Enabled = true; path = String.Empty; } // Conectar dependiendo de la libreria private void OnConnectSSH(object sender, EventArgs e) { // Obtener los datos introducidos var _hostName = hostName.Text; var _user = user.Text; var _password = password.Text; var _port = port.Text; //SSH .NET client = new SshClient(_hostName, Int32.Parse(_port), _user, _password); //Rebex SSH ssh = new Rebex.Net.Ssh(); try { if (spinnerSelected.Equals(GetString(Resource.String.rebexssh))) ClientConnectRebex(ssh); else if (spinnerSelected.Equals(GetString(Resource.String.sshnet))) ClientConnect(client); } catch (Exception ex) { Toast.MakeText(this, ex.Message, ToastLength.Short).Show(); btnConnect.Enabled = true; } } // Conectar el cliente con la libreria SSH .NET private void ClientConnect(SshClient client) { client.Connect(); if (client.IsConnected) { Toast.MakeText(this, "Cliente conectado", ToastLength.Short).Show(); btnDisconnect.Enabled = true; btnBack.Enabled = true; btnConnect.Enabled = false; } string answer = client.RunCommand("ls").Result; string[] words = answer.Split('\n'); path = FormatedPath(client.RunCommand("pwd").Result); List<string> temp = new List<string>(); foreach (var item in words) { if (!String.IsNullOrEmpty(item)) temp.Add(item); } RellenarLista(temp, list); } // Conectar el cliente con la libreria Rebex SSH private void ClientConnectRebex(Rebex.Net.Ssh ssh) { ssh.Connect(hostName.Text, Int32.Parse(port.Text)); ssh.Login(user.Text, password.Text); if (ssh.IsConnected) { Toast.MakeText(this, "Cliente conectado", ToastLength.Short).Show(); btnDisconnect.Enabled = true; btnBack.Enabled = true; btnConnect.Enabled = false; } scripting = ssh.StartScripting(); scripting.DetectPrompt(); scripting.SendCommand("ls"); string line = scripting.ReadUntilPrompt(); string[] words = line.Split(' '); List<string> temp = new List<string>(); foreach (var item in words) { if (!String.IsNullOrEmpty(item)) temp.Add(item); } RellenarLista(temp, list); } // Funcion para cambiar el directorio en Rebex SSH private void ChangeDirectoryRebex(string directory) { scripting.SendCommand("pwd"); string pwd = FormatedPath(scripting.ReadUntilPrompt()) ; scripting.SendCommand("cd " + pwd + directory); string line = ssh.RunCommand("cd " + pwd + directory + "; ls"); string[] words = line.Split('\n'); List<string> temp = new List<string>(); foreach (var item in words) { if (!String.IsNullOrEmpty(item)) temp.Add(item); } RellenarLista(temp, list); } // Funcion para cambiar el directorio en SSH .NET private void ChangeDirectorySSH(string directory) { path = path + directory + "/"; string line = client.RunCommand("cd " + path + ";ls").Result; string[] words = line.Split('\n'); List<string> temp = new List<string>(); foreach (var item in words) { if (!String.IsNullOrEmpty(item)) temp.Add(item); } RellenarLista(temp, list); } // Volver al directorio anterior en Rebex private void BackDirectoryRebex() { scripting.SendCommand("cd .."); scripting.SendCommand("pwd"); string pwd = FormatedPath(scripting.ReadUntilPrompt()) ; scripting.SendCommand("cd " + pwd); //scripting.SendCommand("ls "); string line = ssh.RunCommand("cd " + pwd + "; ls"); string[] words = line.Split('\n'); List<string> temp = new List<string>(); foreach (var item in words) { if (!String.IsNullOrEmpty(item)) temp.Add(item); } RellenarLista(temp, list); } // Volver al directorio anterior en SSH .NET private void BackDirectorySSH() { string pwd = client.RunCommand("cd " + path + "; cd .. ; pwd ").Result; path = FormatedPath(pwd); string line = client.RunCommand("cd " + path + "; ls ").Result; string[] words = line.Split('\n'); List<string> temp = new List<string>(); foreach (var item in words) { if (!String.IsNullOrEmpty(item)) temp.Add(item); } RellenarLista(temp, list); } // Rellenar la lista private void RellenarLista(List<string> temp, ListView list) { list.Adapter = null; ArrayAdapter<String> adaptador = new ArrayAdapter<String>(this, Android.Resource.Layout.SimpleListItem1, temp); list.Adapter = adaptador; } public override bool OnCreateOptionsMenu(IMenu menu) { MenuInflater.Inflate(Resource.Menu.menu_main, menu); return true; } public override bool OnOptionsItemSelected(IMenuItem item) { int id = item.ItemId; if (id == Resource.Id.action_settings) { return true; } return base.OnOptionsItemSelected(item); } // Funcion para obtener la ruta correcta private string FormatedPath(string path) { string replace = string.Empty; if (path != null && path.Contains(" ")) replace = path.Replace(" ", "\\ ").Trim() + "/"; else replace = path; return replace.Trim(); } } } |
Este es el repositorio donde esta subido el proyecto completo