Option to run Racadm locally; handle: logs, exceptions. Separate folders for scripts, logs

This commit is contained in:
2026-01-16 16:21:05 +00:00
parent ecec60554f
commit 803934721f
5 changed files with 1064 additions and 892 deletions

View File

@@ -5,7 +5,7 @@
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{73DED4CD-B2B1-491E-87B7-BC1F11759C53}</ProjectGuid>
<OutputType>Exe</OutputType>
<OutputType>WinExe</OutputType>
<RootNamespace>SSH_Test</RootNamespace>
<AssemblyName>SSH_Test</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
@@ -15,7 +15,7 @@
<IsWebBootstrapper>false</IsWebBootstrapper>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
<PublishUrl>publish\</PublishUrl>
<PublishUrl>D:\Shared\VS\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
@@ -28,6 +28,7 @@
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<UseApplicationTrust>false</UseApplicationTrust>
<PublishWizardCompleted>true</PublishWizardCompleted>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
@@ -52,10 +53,31 @@
<PropertyGroup>
<StartupObject />
</PropertyGroup>
<PropertyGroup>
<TargetZone>LocalIntranet</TargetZone>
</PropertyGroup>
<PropertyGroup>
<GenerateManifests>false</GenerateManifests>
</PropertyGroup>
<PropertyGroup>
<ApplicationManifest>Properties\app.manifest</ApplicationManifest>
</PropertyGroup>
<PropertyGroup>
<ManifestCertificateThumbprint>4A871742B5537E7E2FE907BD60809E3A6E6EEDBF</ManifestCertificateThumbprint>
</PropertyGroup>
<PropertyGroup>
<ManifestKeyFile>SSH_Test_TemporaryKey.pfx</ManifestKeyFile>
</PropertyGroup>
<PropertyGroup>
<SignManifests>true</SignManifests>
</PropertyGroup>
<ItemGroup>
<Reference Include="BouncyCastle.Cryptography, Version=2.0.0.0, Culture=neutral, PublicKeyToken=072edcf4a5328938, processorArchitecture=MSIL">
<HintPath>packages\BouncyCastle.Cryptography.2.6.2\lib\net461\BouncyCastle.Cryptography.dll</HintPath>
</Reference>
<Reference Include="log4net, Version=3.2.0.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>packages\log4net.3.2.0\lib\net462\log4net.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Bcl.AsyncInterfaces, Version=10.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.Bcl.AsyncInterfaces.10.0.0\lib\net462\Microsoft.Bcl.AsyncInterfaces.dll</HintPath>
</Reference>
@@ -72,6 +94,7 @@
<Reference Include="System.Buffers, Version=4.0.5.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>packages\System.Buffers.4.6.1\lib\net462\System.Buffers.dll</HintPath>
</Reference>
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Formats.Asn1, Version=8.0.0.2, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>packages\System.Formats.Asn1.8.0.2\lib\net462\System.Formats.Asn1.dll</HintPath>
@@ -98,6 +121,7 @@
<Reference Include="System.Threading.Tasks.Extensions, Version=4.2.4.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>packages\System.Threading.Tasks.Extensions.4.6.3\lib\net462\System.Threading.Tasks.Extensions.dll</HintPath>
</Reference>
<Reference Include="System.Web" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
@@ -158,7 +182,11 @@
<DependentUpon>Resources.resx</DependentUpon>
<DesignTime>True</DesignTime>
</Compile>
<None Include="log4net.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="packages.config" />
<None Include="Properties\app.manifest" />
<None Include="Properties\DataSources\Profile.datasource" />
<None Include="Properties\DataSources\Program.datasource" />
<None Include="Properties\Settings.settings">
@@ -187,9 +215,7 @@
</BootstrapperPackage>
</ItemGroup>
<ItemGroup>
<None Include="images.png" />
</ItemGroup>
<ItemGroup>
<None Include="SSH_Test_TemporaryKey.pfx" />
<None Include="unicorn.jpg" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />

View File

@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<PublishUrlHistory>publish\</PublishUrlHistory>
<PublishUrlHistory>D:\Shared\VS\|publish\</PublishUrlHistory>
<InstallUrlHistory />
<SupportUrlHistory />
<UpdateUrlHistory />
@@ -10,4 +10,7 @@
<FallbackCulture>en-US</FallbackCulture>
<VerifyUploadedFiles>false</VerifyUploadedFiles>
</PropertyGroup>
<PropertyGroup>
<EnableSecurityDebugging>false</EnableSecurityDebugging>
</PropertyGroup>
</Project>

Binary file not shown.

View File

@@ -1,4 +1,6 @@
using Org.BouncyCastle.Cms;
using log4net;
using log4net.Config;
using Org.BouncyCastle.Cms;
using Renci.SshNet;
using Renci.SshNet.Common;
using System;
@@ -10,6 +12,7 @@ using System.Drawing;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
@@ -19,7 +22,6 @@ using System.Windows.Forms;
using System.Xml;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace SSH_Test
{
@@ -28,37 +30,39 @@ namespace SSH_Test
{
public List<cTask> Tasks = new List<cTask>();
public cConInfo conInfo = new cConInfo("","","","","","","","","");
public cConInfo conInfo = new cConInfo("","","","","","","","","",false);
private List<Profile> Profiles = new List<Profile>();
private static readonly ILog log = LogManager.GetLogger(typeof(Program));
public TastList()
{
var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
InitializeComponent();
// For creating the default profile.json
//Profile profile = new Profile("SSH_Cisco_Tftp_Running", "SSH", new string[] { "copy run tftp://" });
//Profiles.Add(profile);
//profile = new Profile("SSH_Cisco_Tftp_Startup", "SSH", new string[] { "copy startup-config tftp://" });
//Profiles.Add(profile);
//profile = new Profile("SSH_Cisco_Tftp_Enable_Running", "SSH", new string[] { "enable","copy running-config tftp://" });
//Profiles.Add(profile);
//SaveProfile(Profiles, "profile.json");
//Load Profile list from "profile.json"
Profiles = LoadProfile("profile.json");
foreach (Profile p in Profiles)
// Configure Profile list to dropdown menu
try
{
Console.WriteLine("Profile: {0}", p.ProfileName);
foreach (Profile p in Profiles)
{
log.Info(string.Format("Profile: {0}", p.ProfileName));
}
var comboBoxColumn = (DataGridViewComboBoxColumn)dataGridViewTask.Columns[7];
comboBoxColumn.DataSource = Profiles; // Set the data source of the ComboBox column
comboBoxColumn.DisplayMember = "profileName"; // Displayed property name
comboBoxColumn.ValueMember = "profileName"; //The property name of the value
}
catch(Exception ex)
{
log.Error(ex.Message);
}
var comboBoxColumn = (DataGridViewComboBoxColumn)dataGridViewTask.Columns[7];
comboBoxColumn.DataSource = Profiles; // Set the data source of the ComboBox column
comboBoxColumn.DisplayMember = "profileName"; // Displayed property name
comboBoxColumn.ValueMember = "profileName"; //The property name of the value
dataGridViewTask.Refresh();
}
@@ -98,36 +102,57 @@ namespace SSH_Test
hostInfo.device = currentTask.sTaskDevice.ToString();
// print out task
Console.WriteLine("Current task profile {0}:", hostInfo.device);
log.Info(string.Format("Current task profile {0}:", hostInfo.device));
foreach (string c in profile.ProfileCommands)
Console.WriteLine(c);
log.Info(c);
hostInfo.Commands = profile.ProfileCommands;
switch (profile.ProfileType)
{
case "SSH":
Thread thread1 = new Thread(new ParameterizedThreadStart(fSSH));
hostInfo.TftpIP = conInfo.sTftpIP;
hostInfo.SftpIP = conInfo.sTftpIP;
hostInfo.SftpPassword = conInfo.sTftpPassword;
hostInfo.SftpUsername = conInfo.sTftpUsername;
thread1.Start(hostInfo);
try
{
Thread thread1 = new Thread(new ParameterizedThreadStart(fSSH));
hostInfo.TftpIP = conInfo.sTftpIP;
hostInfo.SftpIP = conInfo.sTftpIP;
hostInfo.SftpPassword = conInfo.sTftpPassword;
hostInfo.SftpUsername = conInfo.sTftpUsername;
thread1.Start(hostInfo);
}
catch(Exception ex1)
{
log.Error(ex1);
}
break;
case "SSH_Catalyst":
Thread thread2 = new Thread(new ParameterizedThreadStart(fSSH_Catalyst));
hostInfo.TftpIP = conInfo.sTftpIP;
hostInfo.SftpIP = conInfo.sTftpIP;
hostInfo.SftpPassword = conInfo.sTftpPassword;
hostInfo.SftpUsername = conInfo.sTftpUsername;
thread2.Start(hostInfo);
try
{
Thread thread2 = new Thread(new ParameterizedThreadStart(fSSH_Catalyst));
hostInfo.TftpIP = conInfo.sTftpIP;
hostInfo.SftpIP = conInfo.sTftpIP;
hostInfo.SftpPassword = conInfo.sTftpPassword;
hostInfo.SftpUsername = conInfo.sTftpUsername;
thread2.Start(hostInfo);
}
catch (Exception ex1)
{
log.Error(ex1);
}
break;
case "RAC9":
string command = "";
command = " --nocertwarn -r " + conInfo.sIDracIP + " -u " + conInfo.sIDracUsername + " -p " + conInfo.sIDracPassword + " ";
if (!conInfo.bisLocal)
{
command = " --nocertwarn -r " + conInfo.sIDracIP + " -u " + conInfo.sIDracUsername + " -p " + conInfo.sIDracPassword + " ";
}
foreach (string c in profile.ProfileCommands)
{
@@ -146,18 +171,97 @@ namespace SSH_Test
process.StartInfo.Arguments = command + " " + c;
process.Start();
string result = process.StandardOutput.ReadToEnd();
Console.WriteLine("From RAC9 {0}: {1}", currentTask.sTaskDevice.ToString(), result);
log.Info(string.Format("From RAC9 {0}: {1}", currentTask.sTaskDevice.ToString(), result));
process.WaitForExit();
}
catch (Win32Exception ex)
{
Console.WriteLine($"Error: {ex.Message}. The user likely declined the UAC prompt.");
log.Info(string.Format($"Error: {ex.Message}. The user likely declined the UAC prompt."));
}
}
break;
case "CMD":
command = "/c";
foreach (string c in profile.ProfileCommands)
{
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.UseShellExecute = false; // Required for 'runas' verb
process.StartInfo.Verb = "runas"; // Request administrator privileges
process.StartInfo.WorkingDirectory = Environment.CurrentDirectory; // current working dir
process.StartInfo.RedirectStandardOutput = true;
try
{
string tempfile = DateTime.Now.ToString().Replace(":", "").Replace(" ", "") + ".txt";
process.StartInfo.Arguments = command + " " + c;
process.Start();
string result = process.StandardOutput.ReadToEnd();
log.Info(string.Format("From CMD {0}: {1}", currentTask.sTaskDevice.ToString(), result));
process.WaitForExit();
}
catch (Win32Exception ex)
{
log.Error(ex);
}
}
break;
case "Powershell":
command = " ";
foreach (string c in profile.ProfileCommands)
{
Process process = new Process();
process.StartInfo.FileName = "powershell";
process.StartInfo.UseShellExecute = false; // Required for 'runas' verb
process.StartInfo.Verb = "runas"; // Request administrator privileges
string folderPathPS = Environment.CurrentDirectory + "\\PS";
process.StartInfo.WorkingDirectory = folderPathPS; // current working dir
// check if Powershell Script folder "PS" exists, if not , create one.
if (!Directory.Exists(folderPathPS))
{
Directory.CreateDirectory(folderPathPS);
log.Info(string.Format("Cound not find folder PS, create new {0}", folderPathPS));
}
process.StartInfo.RedirectStandardOutput = true;
try
{
string tempfile = DateTime.Now.ToString().Replace(":", "").Replace(" ", "") + ".txt";
process.StartInfo.Arguments = command + " " + c;
process.Start();
string result = process.StandardOutput.ReadToEnd();
log.Info(string.Format("From Powershell {0}: {1}", currentTask.sTaskDevice.ToString(), result));
process.WaitForExit();
}
catch (Win32Exception ex)
{
log.Error(ex);
}
}
break;
default:
break;
@@ -220,15 +324,8 @@ namespace SSH_Test
}
catch ( Exception ex)
{
log.Error(ex);
}
}
private void dataGridViewTask_CellEndEdit(object sender, DataGridViewCellEventArgs e)
@@ -261,7 +358,8 @@ namespace SSH_Test
break;
case 7: // Profile
Tasks[e.RowIndex].sProfile = (string)dataGridViewTask.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
Console.WriteLine("Task {0}, profile {1}", e.RowIndex, Tasks[e.RowIndex].sProfile);
log.Info(string.Format("Task {0}, profile {1}", e.RowIndex, Tasks[e.RowIndex].sProfile));
break;
default:
break;
@@ -275,7 +373,7 @@ namespace SSH_Test
{
using (Stream stream = File.Open("tasklist.dat", FileMode.Create))
{
Console.WriteLine("Saving Tasklist.dat");
log.Info("Saving Tasklist.dat");
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
binaryFormatter.Serialize(stream, Tasks);
}
@@ -346,226 +444,253 @@ namespace SSH_Test
public void fSSH(object data)
{
cHostInfo hostinfo = (cHostInfo)data;
string host = hostinfo.host;
string device = hostinfo.device;
string username = hostinfo.username;
string password = hostinfo.password;
string tftpIp = hostinfo.TftpIP;
string sftpIp = hostinfo.SftpIP;
string sftpUsername = hostinfo.SftpUsername;
string sftpPassword = hostinfo.SftpPassword;
string[] Commands = hostinfo.Commands;
var client = new SshClient(hostinfo.host, hostinfo.username, hostinfo.password);
Console.WriteLine("From fSSH {0}: Establishing a connection", device);
client.Connect();
Console.WriteLine(client.ConnectionInfo.ServerVersion);
if (client.IsConnected)
try
{
var shellStream = client.CreateShellStream("xterm", 80, 24, 800, 600, 1024);
var output = "";
var result = "";
cHostInfo hostinfo = (cHostInfo)data;
string host = hostinfo.host;
string device = hostinfo.device;
string username = hostinfo.username;
string password = hostinfo.password;
string tftpIp = hostinfo.TftpIP;
string sftpIp = hostinfo.SftpIP;
string sftpUsername = hostinfo.SftpUsername;
string sftpPassword = hostinfo.SftpPassword;
string[] Commands = hostinfo.Commands;
var client = new SshClient(hostinfo.host, hostinfo.username, hostinfo.password);
log.Info(string.Format("From fSSH {0}: Establishing a connection", device));
//wait for "User Name:"
output = shellStream.Expect(new Regex(@"Name:|name:"));
Console.WriteLine("From fSSH {0}: {1}", device, output);
client.Connect();
log.Info(client.ConnectionInfo.ServerVersion);
//send username
shellStream.WriteLine(username);
//wait for "Password:"
output = shellStream.Expect(new Regex(@"word:"));
Console.WriteLine("From fSSH {0}: {1}", device, output);
//send password
shellStream.WriteLine(password);
//wait for "Prompt:"
output = shellStream.Expect(new Regex(@"#"));
Console.WriteLine("From fSSH {0}: {1}", device, output);
output = "";
//create filename
string datetime = DateTime.Now.ToString().Replace(":", "");
datetime = datetime.Replace(" ", "_");
// string filePath = string.Format("{0}_{1}.txt", currentTask.sTaskDevice, datetime.Replace("-", ""));
string filePath = string.Format("{0}_{1}.txt", device, datetime.Replace("-", ""));
foreach (string c in Commands)
if (client.IsConnected)
{
switch (c)
var shellStream = client.CreateShellStream("xterm", 80, 24, 800, 600, 1024);
var output = "";
var result = "";
//wait for "User Name:"
output = shellStream.Expect(new Regex(@"Name:|name:"));
log.Info(string.Format("From fSSH {0}: {1}", device, output));
//send username
shellStream.WriteLine(username);
//wait for "Password:"
output = shellStream.Expect(new Regex(@"word:"));
log.Info(string.Format("From fSSH {0}: {1}", device, output));
//send password
shellStream.WriteLine(password);
//wait for "Prompt:"
output = shellStream.Expect(new Regex(@"#"));
log.Info(string.Format("From fSSH {0}: {1}", device, output));
output = "";
//create filename
string datetime = DateTime.Now.ToString().Replace(":", "");
datetime = datetime.Replace(" ", "_");
// string filePath = string.Format("{0}_{1}.txt", currentTask.sTaskDevice, datetime.Replace("-", ""));
string filePath = string.Format("{0}_{1}.txt", device, datetime.Replace("-", ""));
foreach (string c in Commands)
{
//enable
case "enable":
output = "";
shellStream.WriteLine(c);
//wait for "Password:"
output = shellStream.Expect(new Regex(@"word:"));
Console.WriteLine("From fSSH {0}: {1}", device, c);
//send password
shellStream.WriteLine(password);
break;
// tftp
case string s when Regex.IsMatch(c, @"tftp"):
output = "";
string command = string.Format("{0}{1}/{2}", c, tftpIp, filePath);
Console.WriteLine("From fSSH {0}: {1}", device, command);
//send tftp command
shellStream.WriteLine(command);
switch (c)
{
//enable
case "enable":
output = "";
shellStream.WriteLine(c);
//wait for "Password:"
output = shellStream.Expect(new Regex(@"word:"));
log.Info(string.Format("From fSSH {0}: {1}", device, c));
//wait "<return>" to send "space" and loop until get prompt
while (!Regex.IsMatch(output, "#"))
{
output = shellStream.Expect(new Regex(@"More|<return>|#"));
//send password
shellStream.WriteLine(password);
break;
shellStream.WriteLine(" ");
string[] lines = output.Split('\n');
var output1 = "";
for (int ii = 0; ii < (lines.Length - 1); ii++)
output1 += lines[ii];
Console.WriteLine(output1);
result += output1;
}
break;
default:
shellStream.WriteLine(c);
//wait for "Prompt:"
output = shellStream.Expect(new Regex(@"#"));
Console.WriteLine("From fSSH_Test {0}: {1}", device, output);
break;
// tftp
case string s when Regex.IsMatch(c, @"tftp"):
output = "";
string command = string.Format("{0}{1}/{2}", c, tftpIp, filePath);
log.Info(string.Format("From fSSH {0}: {1}", device, command));
//send tftp command
shellStream.WriteLine(command);
//wait "<return>" to send "space" and loop until get prompt
while (!Regex.IsMatch(output, "#"))
{
output = shellStream.Expect(new Regex(@"More|<return>|#"));
shellStream.WriteLine(" ");
string[] lines = output.Split('\n');
var output1 = "";
for (int ii = 0; ii < (lines.Length - 1); ii++)
output1 += lines[ii];
log.Info(output1);
result += output1;
}
break;
default:
shellStream.WriteLine(c);
//wait for "Prompt:"
output = shellStream.Expect(new Regex(@"#"));
log.Info(string.Format("From fSSH_Test {0}: {1}", device, output));
break;
}
}
}
client.Disconnect();
log.Info(string.Format("From SSH_Test: Disconnected"));
}
catch (Exception e)
{
log.Error("SSH function: cannot run SSH");
log.Error(e);
}
client.Disconnect();
Console.WriteLine("From SSH_Test: Disconnected");
}
public void fSSH_Catalyst(object data)
{
cHostInfo hostinfo = (cHostInfo)data;
string host = hostinfo.host;
string device = hostinfo.device;
string username = hostinfo.username;
string password = hostinfo.password;
string tftpIp = hostinfo.TftpIP;
string sftpIp = hostinfo.SftpIP;
string sftpUsername = hostinfo.SftpUsername;
string sftpPassword = hostinfo.SftpPassword;
string[] Commands = hostinfo.Commands;
var client = new SshClient(hostinfo.host, hostinfo.username, hostinfo.password);
Console.WriteLine("From fSSH_Catalyst {0}: Establishing a connection", device);
client.Connect();
Console.WriteLine("From fSSH_Catalyst {0}: {1}", device, client.ConnectionInfo.ServerVersion);
if (client.IsConnected)
try
{
var shellStream = client.CreateShellStream("xterm", 80, 24, 800, 600, 1024);
var output = "";
var result = "";
var prompt = "";
//output = "";
output = shellStream.Expect(new Regex(@"#"));
Console.WriteLine("From fSSH_Catalyst {0}: {1}", device, output);
prompt = output;
cHostInfo hostinfo = (cHostInfo)data;
shellStream.WriteLine("");
shellStream.Flush();
string host = hostinfo.host;
string device = hostinfo.device;
string username = hostinfo.username;
string password = hostinfo.password;
string tftpIp = hostinfo.TftpIP;
string sftpIp = hostinfo.SftpIP;
string sftpUsername = hostinfo.SftpUsername;
string sftpPassword = hostinfo.SftpPassword;
string[] Commands = hostinfo.Commands;
output = shellStream.Expect(new Regex(prompt));
Console.WriteLine("From fSSH_Catalyst {0}: {1}", device, output);
var client = new SshClient(hostinfo.host, hostinfo.username, hostinfo.password);
log.Info(string.Format("From fSSH_Catalyst {0}: Establishing a connection {1}", device, host));
//create filename
string datetime = DateTime.Now.ToString().Replace(":", "");
datetime = datetime.Replace(" ", "_");
// string filePath = string.Format("{0}_{1}.txt", currentTask.sTaskDevice, datetime.Replace("-", ""));
string filePath = string.Format("{0}_{1}.txt", device, datetime.Replace("-", ""));
foreach (string c in Commands)
client.Connect();
log.Info(string.Format("From fSSH_Catalyst {0}: {1}", device, client.ConnectionInfo.ServerVersion));
if (client.IsConnected)
{
switch (c)
var shellStream = client.CreateShellStream("xterm", 80, 24, 800, 600, 1024);
var output = "";
var result = "";
var prompt = "";
//output = "";
output = shellStream.Expect(new Regex(@"#"));
log.Info(string.Format("From fSSH_Catalyst {0}: {1}", device, output));
prompt = output;
shellStream.WriteLine("");
shellStream.Flush();
output = shellStream.Expect(new Regex(prompt));
log.Info(string.Format("From fSSH_Catalyst {0}: {1}", device, output));
//create filename
string datetime = DateTime.Now.ToString().Replace(":", "");
datetime = datetime.Replace(" ", "_");
// string filePath = string.Format("{0}_{1}.txt", currentTask.sTaskDevice, datetime.Replace("-", ""));
string filePath = string.Format("{0}_{1}.txt", device, datetime.Replace("-", ""));
foreach (string c in Commands)
{
//enable
case "enable":
output = "";
shellStream.WriteLine(c);
//wait for "Password:"
output = shellStream.Expect(new Regex(@"word:"));
Console.WriteLine("From fSSH_Catalyst {0}: {1}", device, c);
//send password
shellStream.WriteLine(password);
break;
// tftp
case string s when Regex.IsMatch(c, @"tftp"):
output = "";
string command = string.Format("{0}{1}/{2}", c, tftpIp, filePath);
Console.WriteLine("From fSSH_Catalyst {0}: {1}", device, command);
//send tftp command
output = "";
shellStream.WriteLine(command);
shellStream.Flush();
//handle shell interaction, wait for "?" then send "enter"
output = shellStream.Expect(new Regex(@"\?"));
Console.WriteLine("From fSSH{0}: {1}", device, output);
while (output.Contains("?"))
{
switch (c)
{
//enable
case "enable":
output = "";
shellStream.WriteLine("");
shellStream.WriteLine(c);
//wait for "Password:"
output = shellStream.Expect(new Regex(@"word:"));
log.Info(string.Format("From fSSH_Catalyst {0}: {1}", device, c));
//send password
shellStream.WriteLine(password);
break;
// tftp
case string s when Regex.IsMatch(c, @"tftp"):
output = "";
string command = string.Format("{0}{1}/{2}", c, tftpIp, filePath);
log.Info(string.Format("From fSSH_Catalyst {0}: {1}", device, command));
//send tftp command
output = "";
shellStream.WriteLine(command);
shellStream.Flush();
output = shellStream.Expect(new Regex(@"\?|#"));
Console.WriteLine("From fSSH_Catalyst {0}: {1}", device, output);
}
break;
default:
shellStream.WriteLine(c);
//wait for "Prompt:"
output = shellStream.Expect(prompt);
Console.WriteLine("From fSSH_Test {0}: {1}", device, output);
break;
//handle shell interaction, wait for "?" then send "enter"
output = shellStream.Expect(new Regex(@"\?"));
log.Info(string.Format("From fSSH_Catalyst{0}: {1}", device, output));
while (output.Contains("?"))
{
output = "";
shellStream.WriteLine("");
shellStream.Flush();
output = shellStream.Expect(new Regex(@"\?|#"));
log.Info(string.Format("From fSSH_Catalyst {0}: {1}", device, output));
}
break;
default:
shellStream.WriteLine(c);
//wait for "Prompt:"
output = shellStream.Expect(prompt);
log.Info(string.Format("From fSSH_Catalyst {0}: {1}", device, output));
break;
}
}
}
}
client.Disconnect();
log.Info(string.Format("From SSH_Catalyst: Disconnected"));
client.Disconnect();
Console.WriteLine("From SSH_Test: Disconnected");
}
catch (Exception e)
{
log.Error("SSH_Catalyst function: cannot run SSH_Catalyst");
log.Error(e);
}
}
private void buttonConf_Click(object sender, EventArgs e)
{
FormConfiguration formConfiguration = new FormConfiguration(conInfo.sTftpIP, conInfo.sSftpIP, conInfo.sSftpUsername, conInfo.sSftpPassword,conInfo.sIDracIP, conInfo.sIDracUsername, conInfo.sIDracPassword);
FormConfiguration formConfiguration = new FormConfiguration(conInfo.sTftpIP, conInfo.sSftpIP, conInfo.sSftpUsername, conInfo.sSftpPassword,conInfo.sIDracIP, conInfo.sIDracUsername, conInfo.sIDracPassword, conInfo.bisLocal);
formConfiguration.ShowDialog();
conInfo.sTftpIP = formConfiguration.Tftp_IP;
conInfo.sSftpIP = formConfiguration.Sftp_IP;
@@ -574,6 +699,7 @@ namespace SSH_Test
conInfo.sIDracIP = formConfiguration.IDRAC_IP;
conInfo.sIDracUsername = formConfiguration.IDRAC_Username;
conInfo.sIDracPassword = formConfiguration.IDRAC_Password;
conInfo.bisLocal = formConfiguration.IDRAC_Local;
}
//Seriallize Profile to a Json file
@@ -589,10 +715,26 @@ namespace SSH_Test
//Deseriallize Profile from a Json file
private static List<Profile> LoadProfile(string filePath)
{
if (File.Exists(filePath))
{
string jsonString = File.ReadAllText(filePath);
return JsonSerializer.Deserialize<List<Profile>>(jsonString);
try
{
string jsonString = File.ReadAllText(filePath);
return JsonSerializer.Deserialize<List<Profile>>(jsonString);
}
catch (Exception ex)
{
//could not read profile.json properly
log.Error("Could not load profile.json");
log.Error(ex);
//return an empty list if file could not be read
return new List<Profile>();
}
}
return new List<Profile>(); // Return an empty list if file doesn't exist
}
@@ -634,8 +776,8 @@ namespace SSH_Test
public string sIDracIP { get; set; }
public string sIDracUsername { get; set; }
public string sIDracPassword { get; set; }
public cConInfo( string TftpIP, string TftpUsername, string TftpPassword, string SftpIP, String SftpUsername, String SftPassword, String IdracIP, String IdracUsername, String IdracPassword)
public bool bisLocal { get; set; }
public cConInfo( string TftpIP, string TftpUsername, string TftpPassword, string SftpIP, String SftpUsername, String SftPassword, String IdracIP, String IdracUsername, String IdracPassword, bool IsLocal)
{
this.sTftpIP = TftpIP;
this.sTftpUsername = TftpUsername;
@@ -646,6 +788,7 @@ namespace SSH_Test
this.sIDracIP = IdracIP;
this.sIDracUsername = IdracUsername;
this.sIDracPassword = IdracPassword;
this.bisLocal = IsLocal;
}
}