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

View File

@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup> <PropertyGroup>
<PublishUrlHistory>publish\</PublishUrlHistory> <PublishUrlHistory>D:\Shared\VS\|publish\</PublishUrlHistory>
<InstallUrlHistory /> <InstallUrlHistory />
<SupportUrlHistory /> <SupportUrlHistory />
<UpdateUrlHistory /> <UpdateUrlHistory />
@@ -10,4 +10,7 @@
<FallbackCulture>en-US</FallbackCulture> <FallbackCulture>en-US</FallbackCulture>
<VerifyUploadedFiles>false</VerifyUploadedFiles> <VerifyUploadedFiles>false</VerifyUploadedFiles>
</PropertyGroup> </PropertyGroup>
<PropertyGroup>
<EnableSecurityDebugging>false</EnableSecurityDebugging>
</PropertyGroup>
</Project> </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;
using Renci.SshNet.Common; using Renci.SshNet.Common;
using System; using System;
@@ -10,6 +12,7 @@ using System.Drawing;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Linq.Expressions; using System.Linq.Expressions;
using System.Reflection;
using System.Text; using System.Text;
using System.Text.Json; using System.Text.Json;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
@@ -19,7 +22,6 @@ using System.Windows.Forms;
using System.Xml; using System.Xml;
using static System.Windows.Forms.VisualStyles.VisualStyleElement; using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace SSH_Test namespace SSH_Test
{ {
@@ -28,37 +30,39 @@ namespace SSH_Test
{ {
public List<cTask> Tasks = new List<cTask>(); 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 List<Profile> Profiles = new List<Profile>();
private static readonly ILog log = LogManager.GetLogger(typeof(Program));
public TastList() public TastList()
{ {
var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
InitializeComponent(); 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" //Load Profile list from "profile.json"
Profiles = LoadProfile("profile.json"); Profiles = LoadProfile("profile.json");
// Configure Profile list to dropdown menu
try
{
foreach (Profile p in Profiles) foreach (Profile p in Profiles)
{ {
Console.WriteLine("Profile: {0}", p.ProfileName); log.Info(string.Format("Profile: {0}", p.ProfileName));
} }
var comboBoxColumn = (DataGridViewComboBoxColumn)dataGridViewTask.Columns[7]; var comboBoxColumn = (DataGridViewComboBoxColumn)dataGridViewTask.Columns[7];
comboBoxColumn.DataSource = Profiles; // Set the data source of the ComboBox column comboBoxColumn.DataSource = Profiles; // Set the data source of the ComboBox column
comboBoxColumn.DisplayMember = "profileName"; // Displayed property name comboBoxColumn.DisplayMember = "profileName"; // Displayed property name
comboBoxColumn.ValueMember = "profileName"; //The property name of the value comboBoxColumn.ValueMember = "profileName"; //The property name of the value
}
catch(Exception ex)
{
log.Error(ex.Message);
}
dataGridViewTask.Refresh(); dataGridViewTask.Refresh();
} }
@@ -98,36 +102,57 @@ namespace SSH_Test
hostInfo.device = currentTask.sTaskDevice.ToString(); hostInfo.device = currentTask.sTaskDevice.ToString();
// print out task // 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) foreach (string c in profile.ProfileCommands)
Console.WriteLine(c); log.Info(c);
hostInfo.Commands = profile.ProfileCommands; hostInfo.Commands = profile.ProfileCommands;
switch (profile.ProfileType) switch (profile.ProfileType)
{ {
case "SSH": case "SSH":
try
{
Thread thread1 = new Thread(new ParameterizedThreadStart(fSSH)); Thread thread1 = new Thread(new ParameterizedThreadStart(fSSH));
hostInfo.TftpIP = conInfo.sTftpIP; hostInfo.TftpIP = conInfo.sTftpIP;
hostInfo.SftpIP = conInfo.sTftpIP; hostInfo.SftpIP = conInfo.sTftpIP;
hostInfo.SftpPassword = conInfo.sTftpPassword; hostInfo.SftpPassword = conInfo.sTftpPassword;
hostInfo.SftpUsername = conInfo.sTftpUsername; hostInfo.SftpUsername = conInfo.sTftpUsername;
thread1.Start(hostInfo); thread1.Start(hostInfo);
}
catch(Exception ex1)
{
log.Error(ex1);
}
break; break;
case "SSH_Catalyst": case "SSH_Catalyst":
try
{
Thread thread2 = new Thread(new ParameterizedThreadStart(fSSH_Catalyst)); Thread thread2 = new Thread(new ParameterizedThreadStart(fSSH_Catalyst));
hostInfo.TftpIP = conInfo.sTftpIP; hostInfo.TftpIP = conInfo.sTftpIP;
hostInfo.SftpIP = conInfo.sTftpIP; hostInfo.SftpIP = conInfo.sTftpIP;
hostInfo.SftpPassword = conInfo.sTftpPassword; hostInfo.SftpPassword = conInfo.sTftpPassword;
hostInfo.SftpUsername = conInfo.sTftpUsername; hostInfo.SftpUsername = conInfo.sTftpUsername;
thread2.Start(hostInfo); thread2.Start(hostInfo);
}
catch (Exception ex1)
{
log.Error(ex1);
}
break; break;
case "RAC9": case "RAC9":
string command = ""; 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) foreach (string c in profile.ProfileCommands)
{ {
@@ -146,18 +171,97 @@ namespace SSH_Test
process.StartInfo.Arguments = command + " " + c; process.StartInfo.Arguments = command + " " + c;
process.Start(); process.Start();
string result = process.StandardOutput.ReadToEnd(); 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(); process.WaitForExit();
} }
catch (Win32Exception ex) 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; break;
default: default:
break; break;
@@ -220,15 +324,8 @@ namespace SSH_Test
} }
catch ( Exception ex) catch ( Exception ex)
{ {
log.Error(ex);
} }
} }
private void dataGridViewTask_CellEndEdit(object sender, DataGridViewCellEventArgs e) private void dataGridViewTask_CellEndEdit(object sender, DataGridViewCellEventArgs e)
@@ -261,7 +358,8 @@ namespace SSH_Test
break; break;
case 7: // Profile case 7: // Profile
Tasks[e.RowIndex].sProfile = (string)dataGridViewTask.Rows[e.RowIndex].Cells[e.ColumnIndex].Value; 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; break;
default: default:
break; break;
@@ -275,7 +373,7 @@ namespace SSH_Test
{ {
using (Stream stream = File.Open("tasklist.dat", FileMode.Create)) 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(); var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
binaryFormatter.Serialize(stream, Tasks); binaryFormatter.Serialize(stream, Tasks);
} }
@@ -345,9 +443,10 @@ namespace SSH_Test
} }
public void fSSH(object data) public void fSSH(object data)
{
try
{ {
cHostInfo hostinfo = (cHostInfo)data; cHostInfo hostinfo = (cHostInfo)data;
string host = hostinfo.host; string host = hostinfo.host;
string device = hostinfo.device; string device = hostinfo.device;
string username = hostinfo.username; string username = hostinfo.username;
@@ -357,15 +456,12 @@ namespace SSH_Test
string sftpUsername = hostinfo.SftpUsername; string sftpUsername = hostinfo.SftpUsername;
string sftpPassword = hostinfo.SftpPassword; string sftpPassword = hostinfo.SftpPassword;
string[] Commands = hostinfo.Commands; string[] Commands = hostinfo.Commands;
var client = new SshClient(hostinfo.host, hostinfo.username, hostinfo.password); var client = new SshClient(hostinfo.host, hostinfo.username, hostinfo.password);
Console.WriteLine("From fSSH {0}: Establishing a connection", device); log.Info(string.Format("From fSSH {0}: Establishing a connection", device));
client.Connect(); client.Connect();
Console.WriteLine(client.ConnectionInfo.ServerVersion); log.Info(client.ConnectionInfo.ServerVersion);
if (client.IsConnected) if (client.IsConnected)
{ {
@@ -376,21 +472,22 @@ namespace SSH_Test
//wait for "User Name:" //wait for "User Name:"
output = shellStream.Expect(new Regex(@"Name:|name:")); output = shellStream.Expect(new Regex(@"Name:|name:"));
Console.WriteLine("From fSSH {0}: {1}", device, output); log.Info(string.Format("From fSSH {0}: {1}", device, output));
//send username //send username
shellStream.WriteLine(username); shellStream.WriteLine(username);
//wait for "Password:" //wait for "Password:"
output = shellStream.Expect(new Regex(@"word:")); output = shellStream.Expect(new Regex(@"word:"));
Console.WriteLine("From fSSH {0}: {1}", device, output); log.Info(string.Format("From fSSH {0}: {1}", device, output));
//send password //send password
shellStream.WriteLine(password); shellStream.WriteLine(password);
//wait for "Prompt:" //wait for "Prompt:"
output = shellStream.Expect(new Regex(@"#")); output = shellStream.Expect(new Regex(@"#"));
Console.WriteLine("From fSSH {0}: {1}", device, output); log.Info(string.Format("From fSSH {0}: {1}", device, output));
output = ""; output = "";
@@ -410,7 +507,8 @@ namespace SSH_Test
shellStream.WriteLine(c); shellStream.WriteLine(c);
//wait for "Password:" //wait for "Password:"
output = shellStream.Expect(new Regex(@"word:")); output = shellStream.Expect(new Regex(@"word:"));
Console.WriteLine("From fSSH {0}: {1}", device, c); log.Info(string.Format("From fSSH {0}: {1}", device, c));
//send password //send password
shellStream.WriteLine(password); shellStream.WriteLine(password);
@@ -420,7 +518,8 @@ namespace SSH_Test
case string s when Regex.IsMatch(c, @"tftp"): case string s when Regex.IsMatch(c, @"tftp"):
output = ""; output = "";
string command = string.Format("{0}{1}/{2}", c, tftpIp, filePath); string command = string.Format("{0}{1}/{2}", c, tftpIp, filePath);
Console.WriteLine("From fSSH {0}: {1}", device, command); log.Info(string.Format("From fSSH {0}: {1}", device, command));
//send tftp command //send tftp command
shellStream.WriteLine(command); shellStream.WriteLine(command);
@@ -436,7 +535,8 @@ namespace SSH_Test
var output1 = ""; var output1 = "";
for (int ii = 0; ii < (lines.Length - 1); ii++) for (int ii = 0; ii < (lines.Length - 1); ii++)
output1 += lines[ii]; output1 += lines[ii];
Console.WriteLine(output1); log.Info(output1);
result += output1; result += output1;
} }
break; break;
@@ -444,21 +544,30 @@ namespace SSH_Test
shellStream.WriteLine(c); shellStream.WriteLine(c);
//wait for "Prompt:" //wait for "Prompt:"
output = shellStream.Expect(new Regex(@"#")); output = shellStream.Expect(new Regex(@"#"));
Console.WriteLine("From fSSH_Test {0}: {1}", device, output); log.Info(string.Format("From fSSH_Test {0}: {1}", device, output));
break; break;
} }
} }
} }
client.Disconnect(); client.Disconnect();
Console.WriteLine("From SSH_Test: Disconnected"); log.Info(string.Format("From SSH_Test: Disconnected"));
}
catch (Exception e)
{
log.Error("SSH function: cannot run SSH");
log.Error(e);
}
} }
public void fSSH_Catalyst(object data) public void fSSH_Catalyst(object data)
{
try
{ {
cHostInfo hostinfo = (cHostInfo)data; cHostInfo hostinfo = (cHostInfo)data;
@@ -473,10 +582,12 @@ namespace SSH_Test
string[] Commands = hostinfo.Commands; string[] Commands = hostinfo.Commands;
var client = new SshClient(hostinfo.host, hostinfo.username, hostinfo.password); var client = new SshClient(hostinfo.host, hostinfo.username, hostinfo.password);
Console.WriteLine("From fSSH_Catalyst {0}: Establishing a connection", device); log.Info(string.Format("From fSSH_Catalyst {0}: Establishing a connection {1}", device, host));
client.Connect(); client.Connect();
Console.WriteLine("From fSSH_Catalyst {0}: {1}", device, client.ConnectionInfo.ServerVersion); log.Info(string.Format("From fSSH_Catalyst {0}: {1}", device, client.ConnectionInfo.ServerVersion));
if (client.IsConnected) if (client.IsConnected)
@@ -487,14 +598,16 @@ namespace SSH_Test
var prompt = ""; var prompt = "";
//output = ""; //output = "";
output = shellStream.Expect(new Regex(@"#")); output = shellStream.Expect(new Regex(@"#"));
Console.WriteLine("From fSSH_Catalyst {0}: {1}", device, output); log.Info(string.Format("From fSSH_Catalyst {0}: {1}", device, output));
prompt = output; prompt = output;
shellStream.WriteLine(""); shellStream.WriteLine("");
shellStream.Flush(); shellStream.Flush();
output = shellStream.Expect(new Regex(prompt)); output = shellStream.Expect(new Regex(prompt));
Console.WriteLine("From fSSH_Catalyst {0}: {1}", device, output); log.Info(string.Format("From fSSH_Catalyst {0}: {1}", device, output));
//create filename //create filename
string datetime = DateTime.Now.ToString().Replace(":", ""); string datetime = DateTime.Now.ToString().Replace(":", "");
@@ -512,7 +625,8 @@ namespace SSH_Test
shellStream.WriteLine(c); shellStream.WriteLine(c);
//wait for "Password:" //wait for "Password:"
output = shellStream.Expect(new Regex(@"word:")); output = shellStream.Expect(new Regex(@"word:"));
Console.WriteLine("From fSSH_Catalyst {0}: {1}", device, c); log.Info(string.Format("From fSSH_Catalyst {0}: {1}", device, c));
//send password //send password
shellStream.WriteLine(password); shellStream.WriteLine(password);
@@ -523,8 +637,8 @@ namespace SSH_Test
output = ""; output = "";
string command = string.Format("{0}{1}/{2}", c, tftpIp, filePath); string command = string.Format("{0}{1}/{2}", c, tftpIp, filePath);
Console.WriteLine("From fSSH_Catalyst {0}: {1}", device, command);
log.Info(string.Format("From fSSH_Catalyst {0}: {1}", device, command));
//send tftp command //send tftp command
output = ""; output = "";
shellStream.WriteLine(command); shellStream.WriteLine(command);
@@ -533,15 +647,16 @@ namespace SSH_Test
//handle shell interaction, wait for "?" then send "enter" //handle shell interaction, wait for "?" then send "enter"
output = shellStream.Expect(new Regex(@"\?")); output = shellStream.Expect(new Regex(@"\?"));
Console.WriteLine("From fSSH{0}: {1}", device, output);
log.Info(string.Format("From fSSH_Catalyst{0}: {1}", device, output));
while (output.Contains("?")) while (output.Contains("?"))
{ {
output = ""; output = "";
shellStream.WriteLine(""); shellStream.WriteLine("");
shellStream.Flush(); shellStream.Flush();
output = shellStream.Expect(new Regex(@"\?|#")); output = shellStream.Expect(new Regex(@"\?|#"));
Console.WriteLine("From fSSH_Catalyst {0}: {1}", device, output); log.Info(string.Format("From fSSH_Catalyst {0}: {1}", device, output));
} }
break; break;
@@ -549,7 +664,8 @@ namespace SSH_Test
shellStream.WriteLine(c); shellStream.WriteLine(c);
//wait for "Prompt:" //wait for "Prompt:"
output = shellStream.Expect(prompt); output = shellStream.Expect(prompt);
Console.WriteLine("From fSSH_Test {0}: {1}", device, output);
log.Info(string.Format("From fSSH_Catalyst {0}: {1}", device, output));
break; break;
} }
@@ -558,14 +674,23 @@ namespace SSH_Test
} }
client.Disconnect(); client.Disconnect();
Console.WriteLine("From SSH_Test: Disconnected"); log.Info(string.Format("From SSH_Catalyst: Disconnected"));
}
catch (Exception e)
{
log.Error("SSH_Catalyst function: cannot run SSH_Catalyst");
log.Error(e);
}
} }
private void buttonConf_Click(object sender, EventArgs 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(); formConfiguration.ShowDialog();
conInfo.sTftpIP = formConfiguration.Tftp_IP; conInfo.sTftpIP = formConfiguration.Tftp_IP;
conInfo.sSftpIP = formConfiguration.Sftp_IP; conInfo.sSftpIP = formConfiguration.Sftp_IP;
@@ -574,6 +699,7 @@ namespace SSH_Test
conInfo.sIDracIP = formConfiguration.IDRAC_IP; conInfo.sIDracIP = formConfiguration.IDRAC_IP;
conInfo.sIDracUsername = formConfiguration.IDRAC_Username; conInfo.sIDracUsername = formConfiguration.IDRAC_Username;
conInfo.sIDracPassword = formConfiguration.IDRAC_Password; conInfo.sIDracPassword = formConfiguration.IDRAC_Password;
conInfo.bisLocal = formConfiguration.IDRAC_Local;
} }
//Seriallize Profile to a Json file //Seriallize Profile to a Json file
@@ -589,11 +715,27 @@ namespace SSH_Test
//Deseriallize Profile from a Json file //Deseriallize Profile from a Json file
private static List<Profile> LoadProfile(string filePath) private static List<Profile> LoadProfile(string filePath)
{ {
if (File.Exists(filePath)) if (File.Exists(filePath))
{
try
{ {
string jsonString = File.ReadAllText(filePath); string jsonString = File.ReadAllText(filePath);
return JsonSerializer.Deserialize<List<Profile>>(jsonString); 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 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 sIDracIP { get; set; }
public string sIDracUsername { get; set; } public string sIDracUsername { get; set; }
public string sIDracPassword { get; set; } public string sIDracPassword { get; set; }
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) 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.sTftpIP = TftpIP;
this.sTftpUsername = TftpUsername; this.sTftpUsername = TftpUsername;
@@ -646,6 +788,7 @@ namespace SSH_Test
this.sIDracIP = IdracIP; this.sIDracIP = IdracIP;
this.sIDracUsername = IdracUsername; this.sIDracUsername = IdracUsername;
this.sIDracPassword = IdracPassword; this.sIDracPassword = IdracPassword;
this.bisLocal = IsLocal;
} }
} }