Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
initial commit
  • Loading branch information
toby11 authored Feb 12, 2020
1 parent 140d91e commit fab3f26
Show file tree
Hide file tree
Showing 5 changed files with 318 additions and 0 deletions.
6 changes: 6 additions & 0 deletions App.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6"/>
</startup>
</configuration>
129 changes: 129 additions & 0 deletions Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace ProxmoxSpiceLauncher
{
class Program
{
// spice proxmox viewer
// based on other peoples code snippets in this thread.
// https://forum.proxmox.com/threads/remote-spice-access-without-using-web-manager.16561/
//
// example command line args
//
// host=192.168.0.1 port=8006 username=root@pam password=xxx node=pve vm=101 viewer="C:\Program Files\VirtViewer v8.0-256\bin\remote-viewer.exe" debug=on

[DllImport("kernel32.dll", EntryPoint = "GetStdHandle", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern IntPtr GetStdHandle(int nStdHandle);

[DllImport("kernel32.dll", EntryPoint = "AllocConsole", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int AllocConsole();

private const int STD_OUTPUT_HANDLE = -11;
private const int MY_CODE_PAGE = 437;
private static bool showConsole = false; //Or false if you don't want to see the console

static void Main(string[] args)
{
string[] requiredArgs = new string[] { "username", "password", "host", "port", "node", "vm", "viewer" };
var parsedArgs = args.Select(s => s.Split('=')).ToDictionary(s => s[0], s => s[1]);

if (parsedArgs.ContainsKey("debug"))
{
if (parsedArgs["debug"] == "on")
showConsole = true;
}

if (showConsole)
{
AllocConsole();
IntPtr stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
Microsoft.Win32.SafeHandles.SafeFileHandle safeFileHandle = new Microsoft.Win32.SafeHandles.SafeFileHandle(stdHandle, true);
FileStream fileStream = new FileStream(safeFileHandle, FileAccess.Write);
System.Text.Encoding encoding = System.Text.Encoding.GetEncoding(MY_CODE_PAGE);
StreamWriter standardOutput = new StreamWriter(fileStream, encoding);
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
}


foreach(var requried in requiredArgs)
{
if (!parsedArgs.ContainsKey(requried))
{
Console.WriteLine("missing argument : " + requried);
Console.ReadLine();
return;
}
}

string Username = parsedArgs["username"];
string Password = parsedArgs["password"];
string Host = parsedArgs["host"];
int Port = Convert.ToInt32(parsedArgs["port"]);
string Node = parsedArgs["node"];
string VmId = parsedArgs["vm"];
string RemoteViewer = parsedArgs["viewer"];

ProxmoxAPI aAPI = new ProxmoxAPI();
aAPI.Username = Username;
aAPI.Password = Password;
aAPI.Host = Host;
aAPI.Port = Port;

try
{
string Ticket = aAPI.RefreshTicket();
}
catch (Exception ex)
{
Console.WriteLine("failed to get ticket : " + ex.Message);
Console.ReadLine();
return;
}

string SpiceCommand = "";
try
{
SpiceCommand = aAPI.GetSpiceCommand(Node, VmId);
}
catch (Exception ex)
{
Console.WriteLine("failed to get spice command : " + ex.Message);
Console.ReadLine();
return;
}

string FileName = "";

try
{
FileName = Path.GetTempFileName();
System.IO.File.WriteAllText(FileName, SpiceCommand);
}
catch (Exception ex)
{
Console.WriteLine("failed to get write temp file : " + ex.Message);
Console.ReadLine();
return;
}

try
{
Process.Start(RemoteViewer, FileName);
}
catch (Exception ex)
{
Console.WriteLine("failed to start remote viewer : " + ex.Message);
Console.ReadLine();
return;
}
}
}
}
36 changes: 36 additions & 0 deletions Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ProxmoxSpiceLauncher")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ProxmoxSpiceLauncher")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5254b2e4-46c0-40bf-a48b-973a33af1cf3")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
85 changes: 85 additions & 0 deletions ProxmoxAPI.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;

namespace ProxmoxSpiceLauncher
{
class ProxmoxAPI
{
public string Username;
public string Password;
public string Host;
public int Port = 8006;
private string Ticket;
private string CSRF;

public ProxmoxAPI()
{

}

public string GetSpiceCommand(string Node, string VMId)
{

ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
HttpWebRequest req;
HttpWebResponse response;


string PostString = string.Format("proxy={0}", Host);
string Url = string.Format("https://{0}:{1}/api2/spiceconfig/nodes/{2}/qemu/{3}/spiceproxy", Host, Port, Node, VMId);
req = WebRequest.Create(Url) as HttpWebRequest;
req.Headers.Add("Cookie", "PVEAuthCookie=" + Ticket);
req.Headers.Add("CSRFPreventionToken", CSRF);
req.Method = "POST";

var data = Encoding.ASCII.GetBytes(PostString);
req.ContentLength = data.Length;
using (var stream = req.GetRequestStream())
stream.Write(data, 0, data.Length);

req.Accept = "*/*";
req.KeepAlive = false;

response = (HttpWebResponse)req.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
return responseString;

}



public string RefreshTicket()
{
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
HttpWebRequest req;
HttpWebResponse response;


string PostString = string.Format("username={0}&password={1}", Username, Password);
string Url = string.Format("https://{0}:{1}/api2/json/access/ticket", Host, Port);
req = WebRequest.Create(Url) as HttpWebRequest;
req.Method = "POST";
req.Accept = "*/*";
req.KeepAlive = false;
var data = Encoding.ASCII.GetBytes(PostString);
req.ContentLength = data.Length;
using (var stream = req.GetRequestStream())
stream.Write(data, 0, data.Length);

response = (HttpWebResponse)req.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
JavaScriptSerializer aSer = new JavaScriptSerializer();
dynamic aJson = aSer.DeserializeObject(responseString);
Ticket = aJson["data"]["ticket"];
CSRF = aJson["data"]["CSRFPreventionToken"];
return Ticket;

}
}
}
62 changes: 62 additions & 0 deletions ProxmoxSpiceLauncher.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{5254B2E4-46C0-40BF-A48B-973A33AF1CF3}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>ProxmoxSpiceLauncher</RootNamespace>
<AssemblyName>ProxmoxSpiceLauncher</AssemblyName>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup>
<StartupObject />
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ProxmoxAPI.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

0 comments on commit fab3f26

Please sign in to comment.